获取结果以显示表1中存在但不存在表2

时间:2015-04-03 05:25:25

标签: sql

我是SQL的新手,无法获得表1中存在的结果而不是表2.我需要显示表2中每个ID的使用次数(包括0)如果没有使用)我可以获得表1中存在的ID,但不能显示表2中不存在的ID。

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时?

谢谢大家

2 个答案:

答案 0 :(得分:1)

试试这个,您可以根据表格结构更改属性名称。

Select t1.id, count(t2.id)

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

Group By t1.id; 

答案 1 :(得分:0)

在这种情况下,您的ID are not unique使用exists countunion之类的内容:

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