我想在我最后一次内部联接中从Name
中选择一个特定列(Products
)。我怎样才能做到这一点?
这是我的SQL语句:
SqlCommand cmd = new SqlCommand("SELECT * FROM CustomerDetails cd INNER JOIN CustomerProducts cp ON cp.CustomerID = cd.Id INNER JOIN Products p ON cp.ProductID = p.ProductID", conn);
到目前为止,我得到了这个,是否有可能有一列?像Name
一样有二氧化碳,工业氧气,因为它们属于同一个Id?谢谢
答案 0 :(得分:0)
SqlCommand cmd = new SqlCommand("select p.[name], cd.* FROM CustomerDetails cd Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id Inner Join Products p ON cp.ProductID = p.ProductID", conn);
编辑:我同意下面的评论,不建议使用cd。*,它应该是cd.Id,cd.CustomerName ......等。
这可以让您将名称组合在一个列中:
;WITH Customers AS
(
select cd.Id, cd.customer ... FROM CustomerDetails cd
)
SELECT stuff(
(
select ', ' + p.[name] FROM Customers cd Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id Inner Join Products p ON cp.ProductID = p.ProductID
FOR XML PATH('')
), 1, 2, '')
, c.Id, c.CustomerName ...
FROM Customers c
答案 1 :(得分:-1)
select p.Name, cd.ColumnA, cd.ColumnB, cd.ColumnC
FROM CustomerDetails cd
Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id
Inner Join Products p ON cp.ProductID = p.ProductID