【问题标题】:get count number of records which respectively exist in another table with null value also获取计数分别存在于另一个表中的记录数为空值
【发布时间】:2015-02-20 12:01:43
【问题描述】:

我有两张桌子。 “listing_messages”和“listing_message_history”。

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`

但它不会返回 count = 0 的 message_id 而 message_id 没有 is_checked=1

【问题讨论】:

  • 您是如何通过标签表记录来格式化这些文本的?

标签: php mysql smarty


【解决方案1】:

一般来说,当您使用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 应该使用第一个表,而不是第二个表。

【讨论】:

  • 您能对此进行查询吗?
猜你喜欢
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
  • 2014-02-21
  • 1970-01-01
  • 2022-01-21
  • 2019-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多