MySQL查询IF EXISTS ELSE IF ELSE

时间:2017-01-24 15:32:24

标签: mysql

我正在尝试做一个简单的,IF,ELSE IF,ELSE语句,这在SQL中相当容易。 由于某种原因,它不会在MySQL中听我的。 它一直告诉我“阅读他妈的手册”,但手册:https://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html

没有说明如何在SELECT部分​​中执行此操作,仅在where之后,我假设这意味着我不能按照我习惯的方式执行此操作。 剩下的问题是,我怎么办呢?

    SELECT EXISTS(SELECT 1 FROM `content` WHERE `ResourceKey`='Test' AND `Language`='en-GB') 
THEN
    SELECT `Text` FROM `content` WHERE `ResourceKey`='Test' AND `Language`='en-GB'; 
ELSE 
    SELECT `Text` FROM `content` WHERE `ResourceKey`='Test' AND `Language`='nl-NL';
END IF;

还有一些信息:

Innodb version: 1.1.8 Protocol version: 10

2 个答案:

答案 0 :(得分:1)

如果您希望查询中有一条记录,则无需使用IF ELSE语句。试试这个:

SELECT `Text` 
FROM `content` 
WHERE `ResourceKey`='Test' AND `Language` ΙΝ ('en-GB', 'nl-NL');
ORDER BY CASE 
            WHEN `Language` = 'en-GB' THEN 1 
            ELSE 2 
         END
LIMIT 1

如果您希望始终返回一些文本,即使没有返回任何记录,也请使用:

SELECT COALESCE(t2.Text, 'No record found') AS Text
FROM (
   SELECT 'en-GB' AS lang UNION ALL 'nl-NL' UNION ALL 'no-lang') AS t1
LEFT JOIN content AS t2 
   ON t1.lang = t2.Language AND t2.ResourceKey = 'Test'  
ORDER BY CASE 
            WHEN t1.lang = 'en-GB' THEN 1 
            WHEN t1.lang = 'nl-NL' THEN 2
            ELSE 3         -- This is the case where t1.lang = 'no-lang'
         END
LIMIT 1

我假设您的数据库中没有Language = 'no-lang'的记录。

答案 1 :(得分:0)

SELECT `Text` 
FROM `content` 
WHERE `ResourceKey` = 'Test'
AND `Language` ΙΝ ('en-GB', 'nl-NL')
ORDER BY if (`Language` = 'en-GB', 1, 2)
LIMIT 1