MySQL - 加入&计算另一个表中的行

时间:2014-05-19 10:52:38

标签: mysql

我有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  

任何暗示我做错了什么?

提前谢谢

3 个答案:

答案 0 :(得分:3)

几种可能的选择,其中之一:

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

答案 1 :(得分:2)

1)带有subselect的解决方案:

SELECT  
    children.id,
    children.data,
    children.parent_id,  
    children.timestamp,  
    (select count(*) from table_votes children.id = table_votes.child_id) as cntVotes
FROM 
  children 
WHERE 
  children.parent_id = 20 
ORDER BY 
  children.timestamp ASC

2)分组解决方案:

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

答案 2 :(得分:0)

我不确定我是否正确理解了您的问题,但对我而言,您似乎想要计算tables_votes中不是儿童的子女数量。尝试以下方法:

select id, data, parent_id, timestamp, child_id
from table_votes join children on children_id.id = table_vote.child_id
where child_id = (select count(child_id) from table_vote)
and parent_id = '20'