问题
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.
回答1:
select person.name, coalesce(car.name, 'no car')
from person
left outer join car on person.id = car.person_id
回答2:
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
回答3:
select person.name, ISNULL(car.name, 'no car')
from person
left join car on person.id = car.person_id
来源:https://stackoverflow.com/questions/14647221/sql-return-row-if-no-result-found