Mysql
 sql >> Base de données >  >> RDS >> Mysql

MySQL - Joindre et compter les lignes d'une autre table

Il y a peu d'options possibles, l'une d'entre elles :

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

Vous pouvez également utiliser votre requête, mais vous devrez ajouter 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