问题
I have two tables photo
and sale
.
photo
has two columns id
and url
.
sale
has two columns photoID
and status
.
The thing is, a photo(row) in photo
table doesn't have to have a record in sale
table so we do not know if a photo is on sale or not.
i.e.
photo
id | url
1 | http://...
2 | http://...
3 | http://...
sale
photoID | status
1 | 'sold'
3 | 'pending'
As you can see, photo having id 2
doesn't have a record in sale
table. What I want to do is to pull all photos from photo
table, and if there is a record of it in sale
table I want the status
info too but in a single query. How can I achieve this ?
Thanks.
回答1:
SELECT p.*, s.status
FROM photo p
LEFT JOIN sale s
ON p.id = s.photoID
回答2:
SELECT p.*, s.status
FROM photo p
INNER JOIN sale s
ON p.id = s.photoID
UNION
SELECT p.*, 'not on sale' AS status
FROM photo p
WHERE NOT EXISTS (
SELECT *
FROM sale s
WHERE p.id = s.photoID
);
来源:https://stackoverflow.com/questions/6845307/fetch-column-if-row-exists-using-mysql