I am trying to write a query in MySQL to fetch a list of images. The problem is that, I want to join another table only when a column is not null.
images:
|id|image |user_id|circle_id|is_deleted|
------------------------------------------------------------------------------------------------------
|1 |cdb10bee27262c597619fdef25bae0eb673f5d5d1b9b33697e40906ad851a25b.jpg|30 |1 |0 |
|2 |9e3213276225b900a3e19262a7761ec3fdf608b95441aa8fbc012f246514d394.jpg|30 |1 |0 |
|3 |a51e104c82de33a804ae0a09e719f3cd7aa205a0830eab4e1e4aa26fd8a6313d.jpg|30 |NULL |0 |
circles_users:
|id|circle_id|user_id|
----------------------
|1 |1 |31 |
users:
|id|username|
-------------
|30|elk |
|31|moose |
Initially, I came up with this, but after inspection, I realised it would not work.
SELECT images.*
FROM images
LEFT JOIN circles_users ON circles_users.circle_id = images.circle_id
WHERE (circles_users.user_id = '31' OR images.circle_id IS NULL)
AND images.user_id = '30'
AND images.is_deleted = '0'
LIMIT 16
I can't seem to get it right anyhow, so I decided to write some pseudo sql to illustrate what I wish to achieve
SELECT images.*
FROM images
CASE
WHEN images.circle_id IS NOT NULL
THEN LEFT JOIN circles_users ON circles_users.circle_id = images.circle_id AND circles_users.user_id = '32'
END CASE
WHERE images.user_id = '30'
AND images.is_deleted = '0'
LIMIT 16
Hope you get what I mean. Thanks for the help.
Basically, I want to fetch all images posted by a user (poster) has if another user is in the circle shared by the poster or if the circle_id is null