Mysql 从父值计算子成员数

Mysql 从父值计算子成员数,mysql,sql,Mysql,Sql,我有一个类似于conversations和conversations\u时间表的表格 对话表格示例 | id | last_active | category_id | |-------------------------------------------| | 1 | 1552462134 | 1 | | 2 | 1552461332 | 1 | | 3 | 1552

我有一个类似于
conversations
conversations\u时间表的表格

对话表格示例

|  id   |   last_active   |   category_id   |
|-------------------------------------------|
|  1    |   1552462134    |        1        |
|  2    |   1552461332    |        1        |
|  3    |   1552462312    |        2        |
|  4    |   1552461772    |        1        |
|  id   |  conversation_id  |  message  |  created_time  |
|--------------------------------------------------------|
|  1    |        1          |  hi       |  1552462066    |
|  2    |        1          |  hello    |  1552462172    |
|  3    |        1          |  world    |  1552462188    |
|  4    |        2          |  another  |  1552462141    |
对话\u时间表表格示例

|  id   |   last_active   |   category_id   |
|-------------------------------------------|
|  1    |   1552462134    |        1        |
|  2    |   1552461332    |        1        |
|  3    |   1552462312    |        2        |
|  4    |   1552461772    |        1        |
|  id   |  conversation_id  |  message  |  created_time  |
|--------------------------------------------------------|
|  1    |        1          |  hi       |  1552462066    |
|  2    |        1          |  hello    |  1552462172    |
|  3    |        1          |  world    |  1552462188    |
|  4    |        2          |  another  |  1552462141    |
我想查询的是计算会话时间线中创建了会话最后一次活动的记录数,其中conversations.category\u id=1

结果会是什么样

|  conversation_id  |  count  |
|         1         |    2    |
|         2         |    1    |

使用
join
groupby
如下

  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

您可以使用以下解决方案,将
JOIN
groupby
结合使用:

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

对不起,我确实编辑了