简体   繁体   English

LEFT OUTER JOIN不显示所有行吗?

[英]LEFT OUTER JOIN not showing all rows?

I'm trying to get data from 2 tables with one SQL statement using joins. 我正在尝试使用联接使用一条SQL语句从2个表中获取数据。 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. 现在有2个项目,一个项目有参与者,另一个项目没有参与者。

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 您必须使用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 这是SQLFiddle演示

I don't think this should be done with a JOIN but rather with a correlated subquery. 我不认为应该使用JOIN来完成,而是使用相关的子查询来完成。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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