我有一个conversations
和conversation_timelines
之类的表
对话表格示例
| id | last_active | category_id |
|-------------------------------------------|
| 1 | 1552462134 | 1 |
| 2 | 1552461332 | 1 |
| 3 | 1552462312 | 2 |
| 4 | 1552461772 | 1 |
conversation_timelines 表格示例
| id | conversation_id | message | created_time |
|--------------------------------------------------------|
| 1 | 1 | hi | 1552462066 |
| 2 | 1 | hello | 1552462172 |
| 3 | 1 | world | 1552462188 |
| 4 | 2 | another | 1552462141 |
我要查询的是计数 conversation_timelines
中有 created_time > conversation's last_active
次会话中的记录数。category_id= 1
结果世界就像
| conversation_id | count |
| 1 | 2 |
| 2 | 1 |
答案 0 :(得分:4)
像下面一样使用join
和group by
SELECT ct.conversation_id,count(ct.message)
FROM conversation_timelines ct
INNER JOIN conversation c on c.id=ct.conversation_id and c.category_id=1
and ct.created_time>c.last_active
GROUP BY ct.conversation_id
答案 1 :(得分:3)
您可以使用以下解决方案,将JOIN
与GROUP BY
结合使用:
SELECT c.id AS `conversation_id`, COUNT(ct.id) AS `count`
FROM conversation c INNER JOIN conversation_timelines ct ON c.id = ct.conversation_id
WHERE ct.created_time > c.last_active AND c.category_id = 1
GROUP BY c.id