Search code examples
phpsqlsubqueryunionwhere-clause

SQL select where conditions 2 if condition 1 doesn't match


I am a little embarassed and feels ashamed as it sounds really simple. But I'm brain freezed on this one

I want to get result of a condition if a first condition didn't match anything. Of course I could use a simple if(!$request) within my php, but I wanted to know if it was not just possible directly trhough my sql request.

I have done a simple OR but of course this will just return both results to each conditions.

SELECT * FROM `menu` WHERE (`id_shop` = $current_shop OR `id_shop` = 0) AND `id_lang` = 1

If there is no entries coresponding to the $current_shop id, I want to get those where id_shop is equal to 0 instead.


Solution

  • If there is no entries coresponding to the $current_shop id, I want to get those where id_shop is equal to 0 instead.

    You can do this with UNION ALL and NOT EXISTS:

    SELECT * 
    FROM `menu` 
    WHERE `id_shop` = ? AND `id_lang` = 1
    UNION ALL 
    SELECT * 
    FROM `menu` 
    WHERE `id_lang` = 1
      AND `id_shop` = 0 
      AND NOT EXISTS (SELECT 1 FROM `menu` WHERE `id_shop` = ? AND `id_lang` = 1)
    

    The first member of the query searches for a match with the given parameters. The second parameter falls back on id_shop 0 if and only if the first member did not return any row.