[英]MySQL - Join & Count rows from another table
I have 3 tables, like:我有 3 个表,例如:
parent(id, name)
children(id, data, parent_id, timestamp)
table_votes(id, user_id, child_id)
I want to get all rows from children
table that have a specific parent_id
, showing also the count of occurences in table_votes
for each one.我想从
children
表中获取具有特定parent_id
所有行,还显示table_votes
中每个行的出现次数。
I try something like the following, but doesn't seem to work, I think I miss all rows from children
that have no entry in table_votes
我尝试了以下类似的方法,但似乎不起作用,我想我错过了在
table_votes
没有条目的所有children
行
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
Any hints what am I doing wrong?任何提示我做错了什么?
Thank you in advance先感谢您
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
:您也可以使用您的查询,但必须添加
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) solution with subselect: 1) 带有子选择的解决方案:
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) solution with group by: 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
i am not sure if i am understanding your question correctly but to me it seems like you want to count the number of children in the tables_votes not in children.我不确定我是否正确理解了您的问题,但对我而言,您似乎想计算 table_votes 中的儿童数量而不是儿童。 try the following:
尝试以下操作:
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.