SQL query to display records from multiple tables
I have following two tables
Table name: thread
pk-> thread_id | thread_title | description | posted_time | Subject
Table name: reply
pk-> reply_id | thread_id | reply
thread_id
is fk
I want to c开发者_运维知识库ount no of replies on each thread, I want output like
thread_id | thread_title | description | posted_time | Subject | No_of_replies
Here's the query I've quickly come up with off of the top of my head:
SELECT
T.Thread_ID
,T.Thread_Title
,T.Description
,T.Posted_Time
,T.Subject
,COUNT(R.Reply_ID) AS No_of_replies
FROM
Thread T
INNER JOIN Reply R ON T.Thread_ID = R.Thread_ID
GROUP BY
T.Thread_ID
,T.Thread_Title
,T.Description
,T.Posted_Time
,T.Subject
This should do what you want.
select t1.*,ifnull(t2.no_of_replies) from thread t1 left join
(select thread_id,count(1) no_of_replies from reply)t2
on t1.thread_id=t2.thread_id
精彩评论