SQL Left将两个表连接成一个

时间:2017-12-07 03:10:13

标签: sql sql-server tsql

列出来自Madison的消费者名称和每个消费者的计算机请求数(如果没有请求则为0)

现在,以下查询说它无法绑定,我认为这是因为我试图将两个表LEFT JOIN连接到Tb_Requests。我不知道其他任何方式。

   SELECT Tb_Consumer.Name, COUNT(tb_requests.Prod_ID) 'Number of Requests'
     FROM Tb_Consumer, Tb_Product 
LEFT JOIN Tb_Requests 
       ON Tb_Consumer.Con_ID = Tb_Requests.Con_ID
    WHERE Tb_Consumer.City = 'Madison'
      AND Tb_Product.Name = 'Computer'
 GROUP BY Tb_Consumer.Name

我有以下表格:

Tb_Consumer - 姓名,城市,Con_ID
Tb_Supplier - 名称,城市,Supp_ID
Tb_Offers - 名称,数量,Prod_ID,Supp_ID
Tb_Product - 名称,Prod_ID
Tb_Requests - 名称,数量,Prod_ID,Con_ID
Tb_Transactions - Tran_ID,Supp_ID,Con_ID,数量,价格

1 个答案:

答案 0 :(得分:2)

您可以使用以下查询解决此问题:

SELECT T1.Name, Count(Tbl_Computer.Prod_ID)
FROM Tbl_Consumer T1 LEFT JOIN 
     (SELECT T2.Prod_ID, T2.Con_ID 
      FROM Tb_Requests T2 
           INNER JOIN Tb_Product T3 
           ON T2.Prod_ID = T3.Prod_ID 
      WHERE T3.Name = 'Computer') AS Tbl_Computer
      ON T1.Con_ID = Tbl_Computer.Con_ID 
 WHERE T1.City = 'Madison'