Fetch column if row exists using MySQL?

冷暖自知 提交于 2019-12-12 01:14:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!