0

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

我认为即使它有效,它也是非常错误的,你能帮忙吗?

4

4 回答 4

2

您不能依赖 a 的子选择的顺序UNION。另请参阅许多其他 Stack Overflow 问题,例如这个:

UNION 和 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...

于 2012-05-14T08:34:53.763 回答
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
于 2012-05-14T08:37:16.697 回答
1

关于您的示例,您希望从中选择所有内容owners并显示id=54 第一个最后的行。

SELECT * FROM owners 
order by case id when 54 then 1 else 0 end, id
于 2012-05-14T08:35:28.320 回答
0

尝试使用括号

(SELECT * FROM owners WHERE id <= 53)
UNION
(SELECT * FROM owners WHERE id >= 55 ORDER BY owner)
UNION
(SELECT * FROM owners WHERE id = 54)
于 2012-05-14T08:33:16.210 回答