MySQL查询使用CASE选择多列

时间:2018-10-15 09:12:12

标签: mysql

我有以下查询可以正常运行:

SELECT Future.enemy_type,
CASE WHEN Future.enemy_type = 'square' THEN Users.color
ELSE ''
END AS color,
CASE WHEN Future.enemy_type = 'square' THEN Users.user_ID
ELSE ''
END AS ID,
CASE WHEN Future.enemy_type = 'headquarters' THEN Users.username
ELSE ''
END AS username,
CASE WHEN Future.enemy_type = 'headquarters' THEN Users.home_lat
ELSE ''
END AS lat
FROM Future
LEFT JOIN Users ON Future.user_ID_affected = Users.user_ID
WHERE Future.time > 1539503510
AND Future.time <= 1539503512
AND Future.user_ID = 10;

但是,有没有更有效的编写方法?我需要根据条件选择一些值(例如,正方形或总部),但我知道CASE只能返回1个值。但是,每次我想返回一个值时,使用新的CASE语句检查条件似乎效率低下。

SO上的某些人建议对类似的查询使用JOIN语句,但是我不确定这在多个条件下如何工作?

谢谢。

1 个答案:

答案 0 :(得分:2)

我喜欢IF()函数的简单陈述:

SELECT
    Future.enemy_type,
    IF (Future.enemy_type = 'square', Users.color, '') AS color,
    IF (Future.enemy_type = 'square', Users.user_ID, '') AS ID,
    IF (Future.enemy_type = 'headquarters', Users.username, '') AS username,
    IF (Future.enemy_type = 'headquarters', Users.home_lat, '') AS lat
FROM Future
LEFT JOIN Users
    ON Future.user_ID_affected = Users.user_ID
WHERE
    Future.time > 1539503510  AND
    Future.time <= 1539503512 AND
    Future.user_ID = 10;