mySQL选择优先级 - 选择一行或另一行(选择默认或“后备”行)

时间:2013-02-04 18:40:59

标签: php mysql

这应该相当简单,但在搜索时找到合适的术语是很棘手的。

在下面的查询中,如果WHERE lang='en'没有返回任何内容,我只需要选择WHERE lang='nl_NL'。换句话说,我想查找所有记录WHERE script='generic',按lang=nl_NL

划分优先顺序
SELECT * FROM international WHERE script='generic' AND (lang = 'nl_NL' OR lang = 'en')

2 个答案:

答案 0 :(得分:2)

SELECT * FROM international WHERE script = 'generic' AND lang = CASE
  WHEN EXISTS(
    SELECT 1
    FROM   international
    WHERE  script = 'generic'
       AND lang   = 'nl_NL'
    LIMIT  1
  ) THEN 'nl_NL'
  ELSE 'en'
END

答案 1 :(得分:1)

以下是获取指定结果集的一种方法示例:

SELECT i.*
  FROM international i
 WHERE i.lang = 'nl_NL'
    OR (i.lang = 'en' 
        AND NOT EXISTS 
        (SELECT 1 FROM international d WHERE d.lang = 'nl_NL')
       )

当你想要应用“script='generic'”谓词时,你的问题并不清楚。

SELECT i.*
  FROM international i
 WHERE ( i.script = 'generic' AND i.lang = 'nl_NL')
    OR ( i.script = 'generic' AND i.lang = 'en'
         AND NOT EXISTS 
           ( SELECT 1
               FROM international d
              WHERE d.lang = 'nl_NL'
                AND d.script='generic'
           )
       )