2015-11-05 68 views
0

我有表,它的查詢結果,我需要通過下列標準命令:將三個MySQL查詢結果爲一個結果排序正確

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) 

我想找出如何保持順序沿三條語句。可能?

回答

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 
+0

這不行。 需要結果返回第一排名,123,121,103然後日期2015-11-05,2015-11-03,然後排名87,76,23等沒有重複。 – sugapablo

1

我假設你真正需要的UNION因爲在其他的答案提到的例子可以沒有它來解決,通常它會影響性能。你可以把它全部包裝在一個新的SELECT聲明中。

SELECT * FROM (
(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) 

) AS NEW_TEMP 
ORDER BY NEW_TEMP.Ranking, NEW_TEMP.List_Date DESC 
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