Use one if with two selects

Asked

Viewed 150 times

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 intend that if you return NULL in this second query, return me a default value, otherwise it gives the query value.

I tried to use an IFNULL, but I was always wrong. You can help perform this in the query??

  • what the default value would be ?

  • because in subselect you use users.iduser and in select user.id_user ??

2 answers

0

0

As you want to return a field from a related table you can use JOIN to do this. In this case you need to return table content ce_users, regardless of whether there is a related record in the table of ce_users_images 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 related record in the table you can use the GROUP BY clauses or add filters in the WHERE or ON clauses.

Mysql JOIN

Browser other questions tagged

You are not signed in. Login or sign up in order to post.