[英]How do I return a row from one table with the number of matching id's from a second table in MySQL?
I have two tables, one of discussions and one of responses. 我有两个表,一个讨论和一个答复。 I'm wondering how to pull back each discussion row along with the number of rows from the responses table with the matching discussion ID. 我想知道如何使用匹配的讨论ID来回退每个讨论行以及响应表中的行数。
discussions
表格discussions
id
creator
date
title
responses
表格responses
id
creator
date
discussion_id
= this is id
from discussions
discussion_id
=这是id
从discussions
So I'd love to be able to get each row of discussions along with a COUNT() of all the responses
rows that have its discussion_id
因此,我希望能够获得每一行讨论以及所有具有其discussion_id
的responses
行的COUNT()
This is about as far as I got: 这是我所得到的:
SELECT
d.id,
d.creator,
d.date,
d.title,
(select count(select * from r where r.discussion_id = d.id) from r) num
FROM
discussions d, responses r
Am I on the right track here? 我在这里走在正确的轨道上吗?
Thanks for your time! 谢谢你的时间!
SELECT d.id, d.creator, d.date, d.title, COUNT(r.id) AS num
FROM discussions AS d
INNER JOIN responses AS r ON r.discussion_id = d.id
GROUP BY d.id
As pointed out by Crwydryn you could also use a LEFT JOIN
instead of the INNER JOIN
. 正如Crwydryn所指出的,您也可以使用LEFT JOIN
而不是INNER JOIN
。 The difference would be that you also count the discussions with no resonses with the LEFT JOIN
- the num
column will then be 0
. 不同之处在于您还可以在没有与LEFT JOIN
共振的情况下计算讨论 - num
列将为0
。
You are close. 你很亲密 Try: 尝试:
SELECT
d.id,
d.creator,
d.date,
d.title,
(select count(*) from r where r.discussion_id = d.id) num
FROM
discussions d
Try like this...simply use group by....it will give what u want 尝试这样......只需使用分组......它会给你想要的东西
SELECT
d.id,
d.creator,
d.date,
d.title,
(Select Count(*) from response where response.id= d.id) as num
FROM
discussions d
Please check the following Query 请检查以下查询
SELECT
d.id,
d.creator,
d.date,
d.title,
count(r.id) NUM
FROM
dicussion d join response r on d.id = r.discussion_id
GROUP BY d.id
I would suggest using a LEFT JOIN. 我建议使用LEFT JOIN。 A standard join will return only Discussions that have a related Response entry, so if the response count is 0 (ie no responses for that discussion), a query with a standard join won't return that discussion record. 标准连接将仅返回具有相关响应条目的讨论,因此如果响应计数为0(即,该讨论没有响应),则具有标准连接的查询将不返回该讨论记录。 Also, this is more performant than a subquery. 此外,这比子查询更高效。
select d.id,
d.creator,
d.date,
d.title,
count(r.id) as num
FROM discussions d
LEFT JOIN responses r on d.id = r.discussion_id
GROUP BY d.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.