gpt4 book ai didi

sql - 加入分组(多对多)

转载 作者:行者123 更新时间:2023-12-01 08:10:17 25 4
gpt4 key购买 nike

我有 2 个表,Product 和 Component

CREATE TABLE Product(
ProductId uniqueidentifier DEFAULT NEWID(),
ProductName nvarchar(25) NOT NULL,
CONSTRAINT PK_Product PRIMARY KEY (ProductId))


CREATE TABLE Component
(
ComponentId uniqueidentifier DEFAULT NEWID(),
ComponentName nvarchar(25) NOT NULL,
CONSTRAINT PK_Component PRIMARY KEY (ComponentId)
)

我需要一个“多对多”的连接,所以我创建了第三个表

CREATE TABLE Product_Component(
idProduct_Component uniqueidentifier DEFAULT NEWID(),
idProduct uniqueidentifier,
idComponent uniqueidentifier,

CONSTRAINT PK_idProduct_Component PRIMARY KEY (idProduct_Component),

CONSTRAINT FK_idComponent FOREIGN KEY (idComponent)
REFERENCES Component (ComponentId),
CONSTRAINT FK_idProduct FOREIGN KEY (idProduct)
REFERENCES Product (ProductId))

我添加了一些数据,现在我可以从表中选择它了。产品可以有很多组件,组件在很多产品中。现在我在 Product 中有 2 行 - Cake 和 Bread。在 Component 中,我有 3 行 - 糖、盐和面粉。我在表 Product_Component 中添加了值,现在我觉得蛋糕包含糖和面粉,面包包含盐和面粉。我使用这样的查询

SELECT Product.ProductName, Component.ComponentName FROM Product_Component
JOIN Component
ON Product_Component.idComponent = Component.ComponentId
JOIN Product
ON Product_Component.idProduct = Product.ProductId
WHERE Product.ProductName = 'Bread'

我看到了面包的所有成分,但每一行都是这样

bread | salt
bread | flour

我想看到这样的东西

bread | salt
| flour
| some other component

我试过了

SELECT Product.ProductName, Component.ComponentName FROM Product_Component
JOIN Component
ON Product_Component.idComponent = Component.ComponentId
JOIN Product
ON Product_Component.idProduct = Product.ProductId
WHERE Product.ProductName = 'Bread'
GROUP BY Product.ProductName

但是我有消息

Column 'Component.ComponentName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

请帮助做出正确的查询。

最佳答案

我认为在您的客户端应用程序中执行此操作会更好、更容易。 SQL 与格式化无关。

但是,如果您想在 SQL 中以任何方式执行此操作,您可以使用 FOR XML将每个分组产品的组件名称串联分组,如下所示:

SELECT 
p.ProductName,
STUFF((
SELECT ', ' + c2.ComponentName
FROM Component AS c2
WHERE c2.idComponent = pc.idComponent
FOR XML PATH (''))
,1,2,'') AS ComponentsNames
FROM Product_Component AS pc
JOIN Component AS c ON pc.idComponent = c.ComponentId
JOIN Product AS p ON pc.idProduct = p.ProductId
WHERE p.ProductName = 'Bread'
GROUP BY p.ProductName;

关于sql - 加入分组(多对多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14871150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com