I have such a query:
SELECT ( SELECT name FROM text WHERE id = 100 ) as name, x, y, w, h FROM pictures WHERE id_obj = 'example' AND picture_type = 20 ORDER BY id DESC LIMIT 1
It works fine as long as there is any row from pictures table that matches criteria. Unfortunatelly (and it’s clear for me why) when there is no picture_type = 20 and id_obj = ‘example’ it produces empty result although there is row with id = 100 in ‘text’ table.
The question is: how to select name from ‘text’ table no matter if picture type and id_obj exists in ‘picture’ table?
I found such a query but I dont like it (it’s too complex and looks awful 🙂
SELECT
( SELECT name FROM text WHERE id = 100 ) as name,
(SELECT x FROM pictures WHERE id_obj = 'example' AND picture_type = 20) as x,
(SELECT y FROM pictures WHERE id_obj = 'example' AND picture_type = 20) as y,
(SELECT w FROM pictures WHERE id_obj = 'example' AND picture_type = 20) as w,
(SELECT h FROM pictures WHERE id_obj = 'example' AND picture_type = 20) as h,
(SELECT id FROM pictures WHERE id_obj = 'example' AND picture_type = 20) as id
ORDER BY id DESC LIMIT 1
Can i make it more clean?
Thanks in advance.
Try with left join, should work fine: