Mysql IF NOT EXISTS然后选择

时间:2013-09-12 16:24:37

标签: mysql not-exists

我尝试通过parent_id和language从表中选择所有行“标签”。 默认语言为en。

list = SELECT * FROM labels WHERE parent_id = x AND lang='de'

if( list.isEmpty() ){
   list = SELECT * FROM labels WHERE parent_id = x AND lang='en'
}

如何仅使用一个MySQL语句来处理这个问题?

非常感谢

2 个答案:

答案 0 :(得分:2)

使用where not existsunion all

SELECT * FROM labels WHERE parent_id = x AND lang='de'
union all
SELECT *
FROM labels
WHERE parent_id = x AND lang = 'en' and
      not exists (SELECT * FROM labels WHERE parent_id = x AND lang='de')

答案 1 :(得分:2)

尝试一下,

SELECT  *
FROM    labels
WHERE   parent_id = x AND
        lang = 
        (
            SELECT  lang
            FROM    labels
            WHERE   parent_id = x
            ORDER   BY FIELD(lang, 'en', 'de') DESC
            LIMIT   1 
        )

FIELD()函数返回列表中的字符串索引。

这是使用JOIN

SELECT  DISTINCT a.*
FROM    labels a
        INNER JOIN
        (
            SELECT  parent_id, lang
            FROM    labels
            WHERE   parent_id = 1
            ORDER   BY FIELD(lang, 'en', 'de') DESC
            LIMIT   1 
        ) b ON a.parent_id = b.parent_id AND
                a.lang = b.lang
WHERE   a.parent_id = 1