MySQL:仅在第一个查询未返回结果时才执行第二个查询

时间:2011-12-02 09:05:46

标签: mysql sql union

我需要这个查询:

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

基本上我只需要一条记录,其中best ='value'和lang = 'x',如果找不到此记录,那么我需要用lang = 'custom'执行第二次查询

MySQL是否足够聪明,可以理解,考虑到有LIMIT 1,当第一个联合查询返回时,他不需要执行第二个查询

我只能做一个查询:

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

但是对于这个查询,我不能说更优先考虑使用lang = 'x'

进行记录

3 个答案:

答案 0 :(得分:5)

您可以使用ORDER BY FIELD()

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

这将解决您的“优先”问题:)

答案 1 :(得分:2)

正确答案是JanHančič的答案(+1)

但是,针对更多未来复杂选择和近乎数据库品牌独立性的替代解决方案可能是:

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

答案 2 :(得分:-1)

您可以在SELECTUNION所在的ORDER BY lang DESC周围包裹另一个LIMIT 1

SELECT * FROM (
  SELECT * FROM best WHERE best = 'value' AND lang = 'x' 
  UNION 
  SELECT * FROM best WHERE best = 'value' AND lang = 'custom' 
)
ORDER BY lang DESC LIMIT 1;