mysql查询使用case选择多列

jm81lzqq  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(316)

我有以下正确的查询:

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;

然而,有没有更有效的方法来写呢?我需要根据条件选择一些值(例如square或headers),但我知道case只能返回1个值。然而,每次我想返回一个值时,用一个新的case语句检查条件似乎效率低下。
so上的一些人建议对类似的查询使用join语句,但我不确定这将如何处理多个条件?
提前谢谢。

lstz6jyr

lstz6jyr1#

我喜欢这个 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;

相关问题