Use an if with two selects

2

I am doing a query, in which the second query can give "NULL" or a value (if there is data).

SELECT *, (SELECT tb1.image FROM ce_users_images tb1
           WHERE tb1.iduser = users.iduser LIMIT 1) AS tmp1
FROM ce_users users
WHERE users.id_user=4
LIMIT 1

I want to return NULL in this second query, return a default value, otherwise it gives the value of the query.

I tried to use an IFNULL, but it always gives me error. Can you help with this in the query ??

    
asked by anonymous 26.06.2017 / 12:47

2 answers

0

You can use the function IFFNULL or COALESCE :

SELECT 
    users.*,
    COALESCE(
    (SELECT 
         tb1.image 
     FROM ce_users_images tb1
     WHERE tb1.iduser = users.id_user
     LIMIT 1),'Nenhuma imagem informada') AS tmp1
FROM ce_users users
WHERE users.id_user=4
LIMIT 1

A little more about the coalesce function: link

    
26.06.2017 / 13:12
0

Since you want to return a field from a related table you can use JOIN to do this. In this case you need to return the contents of the ce_users table, regardless of whether there is a related record in the ce_users_images table LEFT JOIN would work very well.

SELECT 
    users.*, IFNULL(images.image,'img_default.jpg')
FROM
    ce_users AS users
        LEFT JOIN
    ce_users_images AS images ON users.iduser = images.iduser
WHERE
    users.id_user = 4

If there is more than one record listed in the table you can use the GROUP BY clauses or add filters in the WHERE or ON clauses.

MySQL JOIN

    
26.06.2017 / 13:23