2013-02-14 108 views
2

我有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. 

请帮助做出正确的查询。

+0

你想组CONCAT每个产品名称的组件名称的值?同时请发布您尝试的确切查询,查询中的“GROUP BY”在哪里? – 2013-02-14 09:07:54

+0

@MahmoudGamal我编辑了我的查询 – user1947702 2013-02-14 09:12:01

+0

对于每个分组产品名称,您想为组件名称选择什么?你想选择他们在同一行中分组在一起吗?你不能简单地在SQL中做到这一点,更好地删除组,并在客户端应用程序中做这种格式化的东西。 – 2013-02-14 09:12:45

回答

3

我认为在客户端应用程序中执行此操作会更好更容易。 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; 
+0

\\\\非常感谢! – user1947702 2013-02-14 09:25:17

+0

@ user1947702 - 随时欢迎您:)很高兴我能帮忙:) – 2013-02-14 09:25:37