MySQL - 将两行连接到两列

时间:2016-03-15 05:33:13

标签: mysql sql

我有两个表:userphoto。它们看起来像这样:

Database tables

我需要根据useruuid表格上执行SELECT,如果存在urlprofile_photo,则返回background_photo

这些基本上是我需要的最后一个字段(最后两个字段是从photo加入的):

user.nameuser.profile_photo_urluser.background_photo_url

WHERE user.uuid = SOME_UUID

有人可以用这句话指出我正确的方向吗?

2 个答案:

答案 0 :(得分:1)

SELECT user.name, photo_a.url AS profile_photo_url, photo_b.url as background_photo_url FROM user LEFT JOIN photo as photo_a ON user.profile_photo_uuid = photo_a.uuid LEFT JOIN photo as photo_b ON user.background_photo_uuid = photo_b.uuid WHERE user.uuid = SOME_ID

答案 1 :(得分:0)

这应该对你有用

SELECT u.name,u.profile_photo_uuid,u.background_photo_url FROM user u, photo p 
WHERE u.uuid = **userid** AND 
( p.uuid = u.profile_photo_uuid  OR p.uuid = u.background_photo_url);