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 > Complex Count

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 10-17-04, 21:06
raytucson raytucson is offline
Registered User
 
Join Date: Oct 2004
Posts: 2
Complex Count

Hello All,

I have this:
"SELECT *, COUNT(replies.record_ID) " +
"AS number_replies " +
"FROM reports,replies " +
"WHERE replies.record_ID=reports.record_ID " +
"GROUP BY reports.record_ID";

The problem with this is if the replies table has zero records, I don't get my record from the reports table. What would work is a subselect from within COUNT. Something like this.
SELECT *, COUNT(

SELECT * FROM replies
WHERE replies.record_ID=reports.recordID)

FROM REPORTS
WHERE ......

This, of course, is illegal. My situation is that I have a one to many relationship between two tables. The 'many' table has a foreign key to the unique primary key in the 'one' table. I want to select from the 'one' table, then count the number of entries in 'many' that match the primary key.

Thanks in advance, Ray

Last edited by raytucson; 10-17-04 at 21:09.
Reply With Quote
  #2 (permalink)  
Old 10-17-04, 21:54
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
what would work even better is a LEFT OUTER join
Code:
select reports.record_ID
     , reports.foo
     , reports.bar
     , count(replies.record_ID) as number_replies
  from reports
left outer
  join replies 
    on reports.record_ID 
     = replies.record_ID
group 
    by reports.record_ID
     , reports.foo
     , reports.bar
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 10-18-04, 22:18
raytucson raytucson is offline
Registered User
 
Join Date: Oct 2004
Posts: 2
Thanks
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