[SQL]left join與count的問題
有a,b資料表,a是使用者,b是使用者留言訊息
我想找出在使用者留言,有超過0則訊息的留言則數前三名!
也就是「a資料表所有使用者」,在「b資料表裡所有留言版」的留言總數的前三名…
希望sql執行後,結果會是:
aid b_count
5 4
3 2
2 2
目前我自已系統這樣下…
select * from a .... (第1圈迴圈)
select count(aid) as count from b where count>0
and aid=1 2 3 5 6.....(第2個迴圈)
但要把2個sql合併,並顯示b資料表的留言總則數,
降幕排序前三名,我拼不出來sql…
只拼出…(當然是失敗的!!!)
SELECT * FROM a, (SELECT count( aid )AS b_count, aid FROM b) b
WHERE a.aid = b.aid
還請高手指教,謝謝。
資料表如下:
--------------------------
a資料表(留言者)
aid name
1 a
2 b
3 c
4 d
5 e
6 f ...
--------------------------
b資料表(留言訊息)
bid aid message
1 1 test1
2 2 test2
3 2 test3
4 3 test4
5 3 test5
6 5 test6
7 5 test7
8 5 test8
9 6 test9
10 5 test10 ...
--------------------------
最後解決sql:(mysql)
SELECT a.aid, b_count FROM a,
(SELECT count(aid) AS b_count, aid FROM b GROUP BY aid) b
WHERE a.aid = b.aid AND b_count > 0
ORDER BY b_count DESC limit 3
我後來是卡在 count這段語法,不知道要加group by aid …
謝謝大家!^_^
--
習慣一個人在房間裡,安靜地享受書的內容…
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 211.75.186.7
推
11/14 19:18, , 1F
11/14 19:18, 1F
抱歉,寫得太少,沒有好好說明,我重寫了…
※ 編輯: terrybob 來自: 211.75.186.7 (11/14 19:57)
→
11/14 21:10, , 2F
11/14 21:10, 2F
→
11/14 21:10, , 3F
11/14 21:10, 3F
推
11/14 21:40, , 4F
11/14 21:40, 4F
→
11/14 21:42, , 5F
11/14 21:42, 5F
→
11/14 21:43, , 6F
11/14 21:43, 6F
→
11/14 21:43, , 7F
11/14 21:43, 7F
→
11/14 21:43, , 8F
11/14 21:43, 8F
→
11/15 00:19, , 9F
11/15 00:19, 9F
※ 編輯: terrybob 來自: 203.67.40.198 (11/15 00:22)
→
11/15 10:13, , 10F
11/15 10:13, 10F