我有兩個表,hours
和messages
如何連接兩個表並返回0如果值不存在?
hours
表僅具有一個列hour
和插入0〜23的值。
messages
表還有hour
列。
我試圖加入這些表。但我的查詢不起作用。
select hours.hour,ifnull(count(*),0) from hours left join messages on messages.hour = hours.hour group by hours.hour
樣本數據是這裏
消息表
id text sender datetime hour
1 Hi, John Amy 2015-12-10 13:37:25 +0000 13
2 Yup Mike 2015-12-10 15:49:11 +0000 15
3 you there? Mike 2015-12-10 15:49:34 +0000 15
表營業時間
hour
0
1
2
3
4
..
23
我的查詢結果
hour ifnull(count(*),0)
0 1
1 1
2 1
3 1
4 1
...
13 1
14 1
15 2
...
24 1
我想
hour ifnull(count(*),0)
0 0
1 0
2 0
3 0
...
13 1
14 0
15 2
...
24 0
我如何加入兩個表並得到結果像上面?
你需要'RIGHT JOIN' –
@ PM77-1的感謝!但sqlite不支持右連接:( – Mystika