3

我有两张桌子,一张是讨论,一张是回复。我想知道如何从具有匹配讨论 ID 的响应表中拉回每个讨论行以及行数。

桌子discussions

  • id
  • creator
  • date
  • title

桌子responses

  • id
  • creator
  • date
  • discussion_id= 这是iddiscussions

因此,我希望能够获得每一行讨论以及具有responses它的所有行的 COUNT()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

我在正确的轨道上吗?

谢谢你的时间!

4

5 回答 5

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 所指出的,您也可以使用 aLEFT JOIN而不是INNER JOIN. 不同之处在于,您还可以计算与LEFT JOIN- 没有共鸣的讨论 -num然后将是0

于 2013-05-11T13:45:35.487 回答
1

你很亲密。尝试:

SELECT
    d.id,
    d.creator,
    d.date,
    d.title,
    (select count(*) from r where r.discussion_id = d.id) num
FROM 
    discussions d
于 2013-05-11T13:40:19.590 回答
1

像这样尝试...只需使用 group by ....它会给你想要的

 SELECT
        d.id,
        d.creator,
        d.date,
        d.title,
       (Select Count(*) from response where response.id= d.id) as num
    FROM 
        discussions d
于 2013-05-11T13:43:32.527 回答
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 
于 2013-05-11T13:45:39.953 回答
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
于 2013-05-11T13:58:39.717 回答