MySQL - Join & Count rows from another table

前端 未结 3 804
轮回少年
轮回少年 2020-12-12 06:43

I have 3 tables, like:
parent(id, name)
children(id, data, parent_id, timestamp)
table_votes(id, user_id, child_id)

<
3条回答
  •  無奈伤痛
    2020-12-12 07:42

    There are few possible options, one of them:

    SELECT * ,
      (SELECT count(*)
       FROM `table_votes`
       WHERE `children`.`id` = `table_votes`.`child_id`) AS `Count`
    FROM `children`
    WHERE `parent_id` = 20
    

    You can use your query as well, but will have to add GROUP BY:

    SELECT  
     `children`.`id`,  
     `children`.`data`,  
     `children`.`parent_id`,  
     `children`.`timestamp`,  
     COUNT(`v`.`children_id`)  
    FROM `children` LEFT JOIN `table_votes` `v` ON `children`.`id` = `v`.`child_id`  
    WHERE `children`.`parent_id` = 20 
    GROUP BY `children`.`id`, `children`.`data`, `children`.`parent_id`, `children`.`timestamp`,
    ORDER BY `timestamp` ASC
    

提交回复
热议问题