listing_messages
=============
message_id listing_id listing_user third_party_user
1 162 7 32
2 162 7 33
3 162 7 12
listing_message_history
======================
listing_message_history message_id is_checked
1 1 0
2 1 1
3 1 1
4 2 0
5 2 1
6 3 0
搜索条件==> listing_user = 7,is_checked = 1
我想要结果..
message_id count_of_unread_message_history
12
2 1
3 0
我已经提出了一个查询
SELECT count(`lmh`.`message_history_id`) AS COUNT,
`lmh`.`message_id`
FROM `listing_message_history` AS `lmh`
LEFT JOIN `listing_messages` AS `lm` ON `lmh`.`message_id` = `lm`.`message_id`
WHERE `lm`.`third_party_user`=7
AND `lmh`.is_checked=1
GROUP BY `lm`.`message_id`
但它不会返回message_id,其中count = 0,而message_id没有is_checked = 1
答案 0 :(得分:0)
通常,当您使用left join
时,第二个表上的过滤条件应该放在on
子句而不是where
子句中。试试这个:
SELECT count(`lmh`.`message_history_id`) AS COUNT,
`lmh`.`message_id`
FROM `listing_message_history` `lmh` LEFT JOIN
`listing_messages` `lm`
ON `lmh`.`message_id` = `lm`.`message_id` AND
`lm`.`third_party_user` = 7
WHERE `lmh`.is_checked = 1
GROUP BY `lmh`.`message_id`;
此外,您应该使用group by
的第一个表,而不是第二个表。