SQL return row if no result found

2019-08-07 09:39发布

I have two tables:

person
id
name

car
name
person_id

Currently the query goes like:

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

Now this works fine if there is a car associated with a person. However if there isn't, then the person won't get returned. If a person has no car, I want to return a row with the text 'No Car' in column car.name.

3条回答
家丑人穷心不美
2楼-- · 2019-08-07 09:50
select person.name, coalesce(car.name, 'no car')
from person
left outer join car on person.id = car.person_id
查看更多
Deceive 欺骗
3楼-- · 2019-08-07 09:54
select person.name, ISNULL(car.name, 'no car')
from person
left join car on person.id = car.person_id
查看更多
欢心
4楼-- · 2019-08-07 10:11
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
查看更多
登录 后发表回答