Sql 通过连接分组(多对多)
我有两个表,产品和组件Sql 通过连接分组(多对多),sql,tsql,Sql,Tsql,我有两个表,产品和组件 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(), 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))
我添加了一些数据,现在我可以从表中选择它。产品可以有很多组件,组件在很多产品中。现在我有了产品
两行——蛋糕和面包。在组件中
我有3行-糖、盐和面粉。我在表Product\u 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
| flour
| some other component
我看到了面包的所有成分,但每一行都是这样的
bread | salt
bread | flour
我想看看这样的东西
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
| 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中以任何方式执行此操作,您可以使用对每个分组产品的组件名称进行分组串联,如下所示:
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;
是否要对每个产品名称的组件名称值进行分组?另外,请发布您尝试的确切查询,查询中的
分组依据在哪里?@MahmoudGamal我编辑了我的查询对于每个分组的产品名称,您希望为组件名称选择什么?是否要将它们分组在同一行中?你不能简单地在sql中这样做,最好删除group by并在客户端应用程序中进行格式化name@MahmoudGamal我明白了,谢谢you@user1947702-随时欢迎:)很高兴我能帮忙:)