Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: execute the second query only if the first query doesn't return result

Tags:

sql

mysql

union

I need this query:

SELECT * FROM best WHERE best = 'value' AND lang = 'x' 
   UNION 
SELECT * FROM best WHERE best = 'value' AND lang = 'custom' 
LIMIT 1

Basically I just need one record where best = 'value' and lang = 'x', if this record isn't found then I need to execute the second query with lang = 'custom'

Is MySQL smart enough to understand that considering there is the LIMIT 1, when the first query of union returns something he doens't need to execute the second query?

To have just one query I could do:

SELECT * FROM best WHERE best = 'value' AND lang IN ('x','custom') LIMIT 1

But with this query I can't say give more priority to record with lang = 'x'


2 Answers

You could use ORDER BY FIELD():

SELECT
  *
FROM
  best
WHERE
  best = 'value'
  AND lang IN ( 'x', 'custom' )
ORDER BY FIELD ( lang, 'x', 'custom' )
LIMIT
  1

This will take care of your "priority" problem :)

like image 77
Jan Hančič Avatar answered Mar 05 '26 06:03

Jan Hančič


The right anwser is Jan Hančič's answer (+1)

But an alternative solution for more future complex selections and nearly database brand independent may be:

SELECT * FROM (
  SELECT *, 1 as preference 
    FROM best WHERE best = 'value' AND lang = 'x' 
   UNION 
  SELECT *, 2 as preference 
    FROM best WHERE best = 'value' AND lang = 'custom' 
) T ORDER BY preference
LIMIT 1
like image 30
dani herrera Avatar answered Mar 05 '26 06:03

dani herrera