2015-04-03 66 views
0

我是新来的SQL,并且无法获得结果来显示表1中存在但不是表2。我需要显示每个ID有多少次表1已在表2中(包括0,如果没有被使用的话),我可以得到的ID存在于表1中,显示被使用,但不是ID不于表2获得结果显示在表1但不是表2中存在

I am getting: 
     ID Count 
      1 
      1 
      1 
      1 
      1 
      1 
      2 

but need: 
     ID Count 
      1 
      1 
      1 
      0 
      1 
      1 
      0 
      1 
      2 
存在的

我曾尝试:

SELECT COUNT (PID) AS [ID Count] 
FROM SalesOrderProduct 
WHERE PID > = 0 
GROUP BY PID; 

(只此列,我不能得到0值显示)

Table 1: PID, Description 
Table 2: PID, Status 

如何获得显示表2中所有计数的ID的结果,包括使用UNION计数为0时的计数?

谢谢大家

+0

哪个数据库?你试过了什么? – 2015-04-03 05:26:27

+0

恩,“哪个数据库” - 你是指我在用什么程序? (对不起,这是非常新的) 我试过了: SELECT COUNT(SalesOrderProduct.PID)AS [ID Count] FROM SalesOrderProduct GROUP BY PID; (只是此列,我不能得到0值,以显示) 表1:PID,描述 表2:PID,状态 – 2015-04-03 05:34:15

+0

哪个数据库中sqlserver'的'方式或'mysql' – 2015-04-03 05:42:53

回答

0

在这种情况下,你的IDS are not unique使用existscount加上union,如:

select distinct tbl.id, 0 cnt --for ids not exists in table2 
from table1 tbl 
where not exists (select t.id from table2 t where t.id=tbl.id) 
union 
select t1.id, count(t1.id) cnt ----for ids exists in table2 
from table1 t1 
where exists (select t2.id from table2 t2 where t1.id=t2.id) 
group by t1.id 
1

试试这个,你可以改变基于表结构的属性名称。

Select t1.id, count(t2.id) 

From t1 left join t2 
    on (t1.id = t2.id) 

Group By t1.id;