Hundley
Hundley

Reputation: 3577

MySQL - Join two rows to two columns

I have two tables: user and photo. They look like this:

Database tables

I need to perform a SELECT on the user table based on uuid, returning the url for both profile_photo and background_photo, if they exist.

These are essentially the final fields I need (the last two being JOINed from photo):

user.name, user.profile_photo_url, user.background_photo_url

WHERE user.uuid = SOME_UUID

Can somebody point me in the right direction with this statement?

Upvotes: 0

Views: 594

Answers (2)

Rahul Patel
Rahul Patel

Reputation: 639

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

Upvotes: 1

Taj Ahmed
Taj Ahmed

Reputation: 895

This should work for you

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);

Upvotes: 0

Related Questions