iT邦幫忙

1

從多個表選取相同id的個數,不存在時顯示為0

sql中有兩張表

標題a的表當中id 25 26 27 28

留言b的表當中id 26 27 27

請問該如何顯示,在標題a表中的id等於留言b的 id的個數,如果沒有則會顯示為0呢?

我要查詢的結果是 0 1 2 0

語法該怎麼下呢?

謝謝~~!

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
3
wonton
iT邦高手 6 級 ‧ 2016-05-10 08:44:53
最佳解答
SELECT a.id, IFNULL(b.num, 0) AS num FROM a 
LEFT JOIN (SELECT id, COUNT(*) AS num FROM b GROUP BY id) b on b.id=a.id

測試結果:

http://ithelp.ithome.com.tw/upload/images/20160510/20010866YWdonZOZHq.jpg

wonton iT邦高手 6 級 ‧ 2016-05-10 08:47:41 檢舉

IFNULL 是 mysql 的函數,如果是 MSSQL 請用 ISNULL,Oracle 請用 NVL,其他請用 google XDDD

0
daimom
iT邦新手 2 級 ‧ 2016-05-09 15:28:42

declare @t table
(sn int,name varchar(10),category varchar(20),amt int)
declare @y table
(sn int primary key,name varchar(10),category varchar(20),amt int)

insert into @t values (1,'Liu','BCar',1),(1,'Chiu','forcement',3000),(4,'Liu','Enforcement',2500)
insert into @y values (1,'Liu','ACar',1),(2,'Chiu','Enforcement',3000),(3,'Wang','Car',4000),(4,'Liu','Enforcement',2500)


select b.sn,b.name ,count(a.sn)
from @t a right join @y b on a.sn = b.sn
group by a.sn,b.sn,b.name

ans:
sn name _count
1 Liu 2
2 Chiu 0
3 Wang 0
4 Liu 1

0
tzuchin
iT邦新手 5 級 ‧ 2016-05-10 01:38:18

select count(1),b.id from b where b.id in (select id from a where /可以查詢出25.26.27.28的條件/) group by b.id

wonton iT邦高手 6 級 ‧ 2016-05-10 08:49:57 檢舉

這個語法 b.id 中沒有的值,如 25 和 28,就查不出 0 了

tzuchin iT邦新手 5 級 ‧ 2016-05-10 10:48:25 檢舉

嗯.. 是的..
sorry 看錯題目,以為是不顯示0

我要發表回答

立即登入回答