If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Query Problem

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 12-18-05, 20:31
megaultraninja megaultraninja is offline
Registered User
 
Join Date: Oct 2005
Posts: 5
Query Problem

I am having trouble formulating a query on a messageboard like database.

Basically there is a `post` table: with columns:
`post_id`, `title`, `body` etc...

and a `resonse` table with columns:
`response_id`, `post_id`, `title`, `user` etc...

Very simple... But im new to databases and SQL and my problem is...
I can't figure out how to make a query that produces all of the `post` table with the number of responses in each of the posts. I know I some how:

SELECT count(*) FROM response r WHERE r.post_id = whatever.post_id

But I can't figure out to join it with a SELECT * FROM post p like query.
I have tried for an hour or two, and can't figure it out, is it some kind of weird join I haven't thought of.
Any help would be greatly appreciated.

I am using MySQL 4.1 debian.
Reply With Quote
  #2 (permalink)  
Old 12-18-05, 22:46
jfulton jfulton is offline
Registered User
 
Join Date: Apr 2005
Location: Baltimore, MD
Posts: 297
Nested query should work.
Code:
SELECT 
     p.*
     , (SELECT COUNT(*) FROM response r WHERE r.post_id = p.post_id) as num_replies
FROM
     posts p
Reply With Quote
  #3 (permalink)  
Old 12-19-05, 18:32
Zinguy Zinguy is offline
Registered User
 
Join Date: Dec 2005
Posts: 3
The most traditional SQL way is:
Code:
SELECT p.PostID
           ,COUNT(r.ResponseID)
FROM POSTS p
    LEFT JOIN RESPONSES r
        ON r.PostID = p.PostID
GROUP BY p.PostID
Just add all the columns you need from POSTS
and include them in the GROUP BY
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On