MS SQL sql语句返回空结果

时间:2012-04-26 08:34:39

标签: sql sql-server

有两个表:

| idperson |工作量|活性| IDPM |姓名|姓氏|

| idsupportday |日期| fk_person |

和这个SQL语句:

SELECT person.idperson, person.firstname, person.lastname, person.workload,
       person.active, person.idpm, COUNT(supportday.idsupportday) AS SupportDays,
       MIN(supportday.date) AS FirstDate, MAX(supportday.date) AS LastDate
FROM   person
INNER JOIN supportday 
ON         person.idperson = supportday.fk_person
WHERE      (person.active = 1)
GROUP BY   person.idperson, person.firstname, person.lastname, person.workload,
           person.active, person.idpm

现在如果supportday表为空,我也会收到一个空结果。但我仍然希望结果中有person.active=1的所有人。

我需要改变什么?

感谢您的回答。

2 个答案:

答案 0 :(得分:5)

INNER JOIN更改为LEFT OUTER JOIN

SELECT person.idperson, person.firstname, person.lastname, person.workload,
       person.active, person.idpm, COUNT(supportday.idsupportday) AS SupportDays,
       MIN(supportday.date) AS FirstDate, MAX(supportday.date) AS LastDate
FROM   person
LEFT OUTER JOIN supportday 
ON         person.idperson = supportday.fk_person
WHERE      (person.active = 1)
GROUP BY   person.idperson, person.firstname, person.lastname, person.workload,
           person.active, person.idpm
  

仅当两者中至少有一行时,内部联接才会返回行   与连接条件匹配的表。内连接消除了行   与另一个表中的行不匹配。 外连接,   但是,返回至少一个表或视图中的所有行   在FROM子句中提到,只要这些行符合任何WHERE或   有搜索条件。从左表中检索所有行   使用左外连接引用,以及右表中的所有行   在右外连接中引用。

答案 1 :(得分:3)

INNER JOIN更改为LEFT OUTER JOIN