将三个MySQL查询结果合并到一个正确排序的结果中

时间:2015-11-05 14:20:37

标签: mysql sql

我的表的查询结果需要按以下标准排序:

1)排名值为100或更高(从最高到最低排序)

2)List_Date - 过去90天内最新到最旧的。

3)排名小于100的值(从最高到最低排序)

我尝试了以下内容,但意识到它不会按照MySQL文档工作,“因为UNION默认会产生一组无序的行。”

(SELECT Ranking, List_Date 
FROM example_table
WHERE Ranking > 100
ORDER BY Ranking DESC)

UNION

(SELECT Ranking, List_Date 
FROM example_table
WHERE List_Date BETWEEN CURDATE() - INTERVAL 90 DAY AND CURDATE()
ORDER BY List_Date DESC)

UNION

(SELECT Ranking, List_Date 
FROM example_table
WHERE Ranking < 100
ORDER BY Ranking DESC)

我想弄清楚如何保持三个陈述的顺序。可能的?

3 个答案:

答案 0 :(得分:2)

您似乎不需要使用UNION,因为您可以使用OR将条件组合在一起。试试这个:

SELECT Ranking, List_Date 
FROM example_table
WHERE Ranking <> 100 
OR List_Date BETWEEN CURDATE() - INTERVAL 90 DAY AND CURDATE()
ORDER BY Ranking, List_Date DESC

答案 1 :(得分:1)

我假设您确实需要temp/ temp/txt/ ,因为正如其他答案所述,您的示例可以在没有它的情况下解决,通常会影响性能。您可以将它全部包装在新的UNION语句中。

SELECT

答案 2 :(得分:1)

嗯,虽然我收到的答案没有直接解决我的问题,但他们指出了我正确的方向。这是我的解决方案。它有效,但可能不优雅。

SELECT * FROM (
(SELECT (@cnt := @cnt + 1) AS rowNumber, Ranking, List_Date 
FROM example_table
CROSS JOIN (SELECT @cnt := 0) AS dummy
WHERE Ranking > 100
ORDER BY Ranking DESC)

UNION

(SELECT (@cnt := @cnt + 1) AS rowNumber, Ranking, List_Date 
FROM example_table
CROSS JOIN (SELECT @cnt := (SELECT COUNT(*) FROM `example_table `)) AS dummy
WHERE List_Date BETWEEN CURDATE() - INTERVAL 90 DAY AND CURDATE()
ORDER BY List_Date DESC)

UNION

(SELECT (@cnt := @cnt + 1) AS rowNumber, Ranking, List_Date 
FROM example_table
CROSS JOIN (SELECT @cnt := ((SELECT COUNT(*) FROM `example_table `) * 2)) AS dummy
WHERE Ranking < 100
ORDER BY Ranking DESC)
) as T
ORDER BY rowNumber DESC