如何從一個表返回與MySQL中第二個表匹配的id數目相同的行?

[英]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從響應表中提取每個討論行以及行數。

table discussions

  • id
  • id
  • creator
  • 創造者
  • date
  • 日期
  • title
  • 標題

table responses

  • id
  • id
  • creator
  • 創造者
  • date
  • 日期
  • discussion_id = this is id from discussions
  • discussion_id =來自討論的id

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的所有響應行的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!

謝謝你的時間!

5 个解决方案

#1


1  

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

#2


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

As pointed out by Crwydryn you could also use a LEFT JOIN instead of the 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.

正如Crwydryn所指出的,您也可以使用左連接而不是內連接。不同之處在於,您還可以計算與左連接沒有共振的討論——然后num列將為0。

#3


1  

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 

#4


1  

Try like this...simply use group by....it will give what u want

這樣的嘗試……簡單地使用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

#5


1  

I would suggest using a LEFT JOIN. A standard join will return only Discussions that have a related Response entry, so if the response count is 0 (i.e. no responses for that discussion), a query with a standard join won't return that discussion record. Also, this is more performant than a subquery.

我建議使用左連接。標准連接只返回具有相關響應條目的討論,因此如果響應計數為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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/05/11/720d11adf7ea559fcb30e46e1fd501e0.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com