提问人:Stylus 提问时间:7/29/2023 最后编辑:Stylus 更新时间:7/29/2023 访问量:46
在mysql ORDER BY中,是否可以在IF条件中使用CASE
In mysql ORDER BY, is it possible to use CASE inside IF condition
问:
我有一个 SELECT 查询,其中有 ORDER BY
我想要的是
if(type=2 AND (station=0 OR station=1)) 那么
SELECT * FROM table
ORDER BY CASE type
WHEN 1 OR 2 THEN 1
WHEN 3 THEN 2
ELSE 4
END,CAST(choice AS SIGNED ) DESC
if(type=2 AND station=2) 那么
SELECT * FROM table
ORDER BY CASE type
WHEN 1 THEN 1
WHEN 2 THEN 2
WHEN 3 THEN 3
ELSE 4
END,CAST(choice AS SIGNED ) DESC
是否可以将 CASE 置于 IF 条件中以及如何放置?
我试过了
SELECT * FROM table
ORDER BY IF(type=2 AND (station=0 OR station=1))
{
CASE type
WHEN 1 OR 2 THEN 1
WHEN 3 THEN 2
ELSE 4
END,CAST(choice AS SIGNED ) DESC
}
ELSEIF(type=2 AND station=2)
{
CASE type
WHEN 1 THEN 1
WHEN 2 THEN 2
WHEN 3 THEN 3
ELSE 4
END,CAST(choice AS SIGNED ) DESC,
}
答:
0赞
Ergest Basha
7/29/2023
#1
我认为您不能将 case 语句嵌套在 if 语句中。
但是您可以将 case 嵌套在 case 语句中。
尝试
SELECT * FROM `table`
ORDER BY CASE WHEN type=2 AND (station=0 OR station=1)
THEN
CASE type
WHEN 1 OR 2 THEN 1
WHEN 3 THEN 2
ELSE 4
END
WHEN type=2 AND station=2
THEN
CASE WHEN 1 THEN 1
WHEN 2 THEN 2
WHEN 3 THEN 3
ELSE 4
END
END ,CAST(choice AS SIGNED ) DESC
请参阅此处的示例
评论
0赞
Stylus
7/29/2023
谢谢你的回答。我尝试了查询并按预期得到了结果。
评论