简体   繁体   中英

LEFT OUTER JOIN not showing all rows?

I'm trying to get data from 2 tables with one SQL statement using joins. The idea is quite simple. A project has participants, and in a project overview I want to show the project info with the amount of participants.

Right now there are 2 projects, one project with participants and the other project without participants.

I use this query:

SELECT SQL_CALC_FOUND_ROWS `p`.`id`,
       `p`.`title`, 
       `p`.`live`, 
       `p`.`startDate`,
       `p`.`endDate`, 
       COUNT(`part`.`id`) AS `participants`
FROM `projects` `p`
LEFT OUTER JOIN `participants` `part`
    ON `p`.`id`  = `part`.`projectid`
ORDER BY `p`.`live` DESC, 
         `p`.`startDate` DESC
LIMIT 0,10

Problem is, this query only returns the project with participants and the one without participants is left out.

What am I doing wrong here?

You have to use GROUP BY

SELECT SQL_CALC_FOUND_ROWS `p`.`id`,
       `p`.`title`, 
       `p`.`live`, 
       `p`.`startDate`,
       `p`.`endDate`, 
       COUNT(`part`.`id`) AS `participants`
FROM `projects` `p`
LEFT OUTER JOIN `participants` `part`
    ON `p`.`id`  = `part`.`projectid`
GROUP BY `p`.`id`,
         `p`.`title`, 
         `p`.`live`, 
         `p`.`startDate`,
         `p`.`endDate`
ORDER BY `p`.`live` DESC, 
         `p`.`startDate` DESC
LIMIT 0,10

Here is SQLFiddle demo

I don't think this should be done with a JOIN but rather with a correlated subquery.

SELECT SQL_CALC_FOUND_ROWS `p`.`id`,
   `p`.`title`, 
   `p`.`live`, 
   `p`.`startDate`,
   `p`.`endDate`, 
   (SELECT COUNT(`part`.`id`) FROM `participants` `part` WHERE `part`.`projectid` = `p`.`id`) AS `participants`
FROM `projects` `p`
ORDER BY `p`.`live` DESC, 
     `p`.`startDate` DESC
LIMIT 0,10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM