我有两个表,一个是讨论,另一个是回复。我想知道如何使用匹配的讨论ID拉回每个讨论行以及响应表中的行数。
discussions
id
creator
date
title
responses
id
creator
date
discussion_id
=这是来自id
discussions
因此,我希望能够获得每一行讨论以及所有responses
行的discussion_id
这就是我的意思:
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
我在这里走在正确的轨道上吗?
谢谢你的时间!
答案 0 :(得分:2)
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
正如Crwydryn所指出的,您也可以使用LEFT JOIN
代替INNER JOIN
。不同之处在于,您还会计算讨论时与LEFT JOIN
没有共鸣 - num
列将为0
。
答案 1 :(得分:1)
你很亲密。尝试:
SELECT
d.id,
d.creator,
d.date,
d.title,
(select count(*) from r where r.discussion_id = d.id) num
FROM
discussions d
答案 2 :(得分:1)
尝试这样......只需使用分组......它会给你想要的东西
SELECT
d.id,
d.creator,
d.date,
d.title,
(Select Count(*) from response where response.id= d.id) as num
FROM
discussions d
答案 3 :(得分:1)
请检查以下查询
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
答案 4 :(得分:1)
我建议使用LEFT JOIN。标准连接将仅返回具有相关响应条目的讨论,因此如果响应计数为0(即,没有针对该讨论的响应),则具有标准连接的查询将不返回该讨论记录。此外,这比子查询更高效。
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