如果找不到结果,则返回SQL

时间:2013-02-01 13:20:53

标签: sql postgresql null left-join

我有两张桌子:

person
id
name

car
name
person_id

目前查询如下:

SELECT
person.name
car.name
FROM
person, car
WHERE
person.id = car.person_id

现在,如果有人与某人相关联,这项工作正常。但是,如果没有,那么这个人就不会被退回。如果一个人没有车,我想在第'No Car'栏中返回包含car.name文字的行。

3 个答案:

答案 0 :(得分:3)

select person.name, coalesce(car.name, 'no car')
from person
left outer join car on person.id = car.person_id

答案 1 :(得分:0)

SELECT person.name, CASE WHEN car.name IS NULL THEN 'no car' ELSE car.name END 
FROM person
LEFT JOIN car ON person.id = car.person_id

答案 2 :(得分:-1)

select person.name, ISNULL(car.name, 'no car')
from person
left join car on person.id = car.person_id