简体   繁体   English

在mysql中选择UNION和ORDER BY ..怎么样?

[英]SELECT UNION and ORDER BY in mysql.. how to?

i would like to get from a single table, all rows, but order them in different ways. 我想从单个表中获取所有行,但是以不同的方式对它们进行排序。 For example i write 比如说我写

(SELECT * FROM table1
ORDER BY fieldA ASC LIMIT 3
)
UNION
(
SELECT * FROM table1
ORDER BY FieldB DESC
)

It works, excpet that the second order by (FIELDB DESC) is ignored... Somebody know Why ? 它的工作原理是,(FIELDB DESC)的二阶被忽略了...有人知道为什么? Thank you 谢谢

The UNION operator performs an implied sort as part of the union operation (IIRC, on the key column(s)). UNION运算符执行隐含排序作为联合操作的一部分(IIRC,在关键列上)。

If you want other sorting in the result, you have to apply an ORDER BY to the unioned selection. 如果要在结果中进行其他排序,则必须将ORDER BY应用于联合选择。

In your case, you need some way to distinguish between the first selection and the second, so that you can order the union properly. 在您的情况下,您需要某种方式来区分第一个选择和第二个选择,以便您可以正确地订购联合。 Something like (untested): 像(未经测试)的东西:

(SELECT table1.*, 0 AS TMP_ORDER FROM table1 ORDER BY fieldA ASC LIMIT 3)
UNION
(SELECT table1.*, 1 AS TMP_ORDER FROM table1)
ORDER BY TMP_ORDER ASC, 
CASE WHEN TMP_ORDER = 0 THEN fieldA ELSE 0 END ASC, 
CASE WHEN TMP_ORDER = 1 THEN fieldB ELSE 0 END DESC

The problem with this approach is that you'll have duplicates for the three rows selected as part of the first query in the UNION (since the columns don't totally match). 这种方法的问题在于,您将在UNION作为第一个查询的一部分选择的三行重复(因为列不完全匹配)。

Are you sure you can't use two SELECT statments instead? 您确定不能使用两个SELECT语句吗?

You can declare the second SELECT as a fixed result.. 您可以将第二个SELECT声明为固定结果..

SELECT  'First select option' AS something

UNION

SELECT something
FROM(
    (SELECT something
    FROM SomeTable
    ORDER BY something ASC)) FixedResult

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM