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
我认为即使它有效,它也是非常错误的,你能帮忙吗?
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
我认为即使它有效,它也是非常错误的,你能帮忙吗?
您不能依赖 a 的子选择的顺序UNION
。另请参阅许多其他 Stack Overflow 问题,例如这个:
像这样做:
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
...
如果您只想将 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
关于您的示例,您希望从中选择所有内容owners
并显示id=54
第一个最后的行。
SELECT * FROM owners
order by case id when 54 then 1 else 0 end, id
尝试使用括号
(SELECT * FROM owners WHERE id <= 53)
UNION
(SELECT * FROM owners WHERE id >= 55 ORDER BY owner)
UNION
(SELECT * FROM owners WHERE id = 54)