我有3张桌子,例如:
parent(id, name)
children(id, data, parent_id, timestamp)
table_votes(id, user_id, child_id)

我想从children表中获得具有特定parent_id的所有行,还显示每个table_votes中出现的次数。

我尝试执行以下操作,但似乎无法正常工作,我想我错过了children中所有在table_votes中没有条目的行

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 ORDER BY `timestamp` ASC


有什么提示我在做什么错吗?

先感谢您

最佳答案

可能的选择很少,其中之一是:

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


您也可以使用查询,但必须添加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

关于mysql - MySQL-连接和计算另一个表中的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45087565/

10-16 00:29