Stackoverflowers, 我想从MYSQL表中选择并在MYSQL查询的末尾显示ID 54,我制作了以下代码,但它与ORDER冲突:
SELECT * FROM owners WHERE id <= 53
UNION
SELECT * FROM owners WHERE id >= 55
ORDER BY owner
UNION
SELECT * FROM owners WHERE id = 54
我认为即使它有效也很麻烦,你能帮忙吗?
答案 0 :(得分:2)
您不能依赖UNION
子选择的顺序。另请参阅许多其他Stack Overflow问题,例如:
Weird result with UNION and ORDER BY
这样做:
SELECT * FROM owners
-- Order by "ID category" first
ORDER BY CASE WHEN ID <= 53 THEN 1
WHEN ID >= 55 THEN 2
WHEN ID = 54 THEN 3 END,
-- Then, within "category 55", order by owner, too
CASE WHEN ID <= 53 THEN ''
WHEN ID >= 55 THEN owner
WHEN ID = 54 THEN '' END
您可能需要稍微调整第二个ORDER BY
表达式,因为我不确定您要对owner
的排序做什么...
答案 1 :(得分:2)
如果您只想将54放在最后,也许您可以将查询缩短为:
SELECT * FROM owners
WHERE id <= 53 or id >= 55 or id = 54
ORDER BY
id = 54,
owner
首先进行错误排序,最后进行真正的排序。其他数据库这样做:
SELECT * FROM owners
WHERE id <= 53 or id >= 55 or id = 54
ORDER BY
case when id = 54 then 1 else 0 end,
owner
但这很有趣,完全取消了这个条件:
SELECT * FROM owners
ORDER BY
case when id = 54 then 1 else 0 end,
owner
答案 2 :(得分:1)
关于您的示例,您要从owners
中选择所有内容,并最后显示id=54
第一行的行。
SELECT * FROM owners
order by case id when 54 then 1 else 0 end, id
答案 3 :(得分:0)
尝试使用括号
(SELECT * FROM owners WHERE id <= 53)
UNION
(SELECT * FROM owners WHERE id >= 55 ORDER BY owner)
UNION
(SELECT * FROM owners WHERE id = 54)