我有2个表,产品和组件集团通过与加盟(多对多)
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))
我增加了一些数据,现在我可以从表select
。产品可以有很多组件,组件在许多产品中。现在我在Product
2行 - 蛋糕和面包。在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.
请帮助做出正确的查询。
你想组CONCAT每个产品名称的组件名称的值?同时请发布您尝试的确切查询,查询中的“GROUP BY”在哪里? – 2013-02-14 09:07:54
@MahmoudGamal我编辑了我的查询 – user1947702 2013-02-14 09:12:01
对于每个分组产品名称,您想为组件名称选择什么?你想选择他们在同一行中分组在一起吗?你不能简单地在SQL中做到这一点,更好地删除组,并在客户端应用程序中做这种格式化的东西。 – 2013-02-14 09:12:45