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 > SQL help on aggregates

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 05-27-11, 16:04
ozzii ozzii is offline
Registered User
 
Join Date: Mar 2007
Posts: 194
SQL help on aggregates

Hi,

Am using the folling query to give me a list of jobs, the number of applications for those jobs and the number of times the advert has been viewed.

Code:
SELECT jobs.job_id
         , jobs.job_title
         , COUNT(apps.app_id) AS applicantions
         , COUNT(log.job_view_id) AS job_views
FROM tbl_jobs AS jobs 
LEFT JOIN tbl_applications AS apps ON jobs.job_id = apps.job_id 
LEFT JOIN tbl_job_view_log AS log ON jobs.job_id = log.job_id 
GROUP BY jobs.job_id
However I am getting incorrect results. If there is 1 application and the advert has been viewed twice am getting a count of 2 for applications as well.

Can some one point me in the right direction.

Cheers.
Reply With Quote
  #2 (permalink)  
Old 05-27-11, 17:29
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
you're seeing cross join effects, when multiple joined rows are matched with multiple joined rows

instead of joining and joining and then grouping, you should be grouping and grouping and then joining, if you know what i mean
Code:
SELECT jobs.job_id
     , jobs.job_title
     , subquery_a.applications
     , subquery_v.job_views
  FROM tbl_jobs AS jobs 
LEFT OUTER
  JOIN ( SELECT job_id
              , COUNT(*) AS applications
           FROM tbl_applications 
         GROUP
             BY job_id
       ) AS subquery_a 
    ON subquery_a.job_id = jobs.job_id 
LEFT OUTER
  JOIN ( SELECT job_id
              , COUNT(*) AS job_views
           FROM tbl_job_view_log 
         GROUP
             BY job_id
       ) AS subquery_v
    ON subquery_v.job_id = jobs.job_id
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 05-29-11, 09:24
ozzii ozzii is offline
Registered User
 
Join Date: Mar 2007
Posts: 194
Quote:
you're seeing cross join effects, when multiple joined rows are matched with multiple joined rows

instead of joining and joining and then grouping, you should be grouping and grouping and then joining, if you know what i mean

Many 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