2016-03-04 44 views
0

我有3個不同的查詢,通過不同的參數相同的結果基本排序和我想的MySQL返回它們的結果合併成3個不同的列:MySQL的:合併由第3個欄查詢結果

SELECT `text` AS `popular` FROM `searches` WHERE `text` LIKE 'Tyr%' ORDER BY `hits` DESC LIMIT 10 
SELECT `text` AS `recent` FROM `searches` WHERE `text` LIKE 'Tyr%' ORDER BY `datetime` DESC LIMIT 10 
SELECT `text` AS `matches` FROM `searches` WHERE `text` LIKE 'Tyr%' ORDER BY `matches` DESC LIMIT 10 

第一個查詢返回這樣的:

| popular | 
| A | 
| B | 
| C | 

第二個查詢返回此:

| recent | 
| B | 
| C | 
| A | 

丙戌ERY返回此:

| matches | 
| C | 
| A | 
| B | 

我想合併這些結果讓我得到這個使用單個查詢:

| popular | recent | matches | 
| A | B | C | 
| B | C | A | 
| C | A | B | 

這是我試過到目前爲止,但結果我得到的是完全弄亂。

SELECT * FROM 
    (SELECT `text` AS `popular` FROM `searches` WHERE `text` LIKE 'Tyr%' ORDER BY `hits` DESC LIMIT 10) AS A 
    JOIN (SELECT `text` AS `recent` FROM `searches` WHERE `text` LIKE 'Tyr%' ORDER BY `datetime` DESC LIMIT 10) AS B ON 1=1 
    JOIN (SELECT `text` AS `matches` FROM `searches` WHERE `text` LIKE 'Tyr%' ORDER BY `matches` DESC LIMIT 10) AS C ON 1=1 
+0

你想要的結果是在3個查詢相同的是在同一行還是你只想統一3次的查詢,並得到一個共有30條記錄?請舉例說明你的數據是什麼樣的,以及你對輸出的期望。 –

回答

1

嘗試這樣:

select t1.popular, t2.recent, t3.matches 
from  (SELECT @rownum1 := @rownum1 + 1 AS rank, `text` AS `popular` FROM `searches` t, (SELECT @rownum1 := 0) r WHERE `text` LIKE 'Tyr%' ORDER BY `hits`  DESC LIMIT 10) t1 
inner join (SELECT @rownum2 := @rownum2 + 1 AS rank, `text` AS `recent` FROM `searches` t, (SELECT @rownum2 := 0) r WHERE `text` LIKE 'Tyr%' ORDER BY `datetime` DESC LIMIT 10) t2 on t1.rank = t2.rank 
inner join (SELECT @rownum3 := @rownum3 + 1 AS rank, `text` AS `matches` FROM `searches` t, (SELECT @rownum3 := 0) r WHERE `text` LIKE 'Tyr%' ORDER BY `matches` DESC LIMIT 10) t3 on t2.rank = t3.rank 
-1

您可以使用MySQL 'UNION statement',它可以合併多個選擇並將其作爲一個輸出返回。因此,嘗試:

SELECT `text` AS `popular` FROM `searches` WHERE `text` LIKE 'Tyr%' ORDER BY `hits` DESC LIMIT 10 UNION SELECT `text` AS `recent` FROM `searches` WHERE `text` LIKE 'Tyr%' ORDER BY `datetime` DESC LIMIT 10 UNION SELECT `text` AS `matches` FROM `searches` WHERE `text` LIKE 'Tyr%' ORDER BY `matches` DESC LIMIT 10 
+0

不考慮查詢返回由於ORDER BY語句引起的錯誤的事實,這並不是我正在查找的內容,因爲我想返回組織爲3列的3個查詢結果。 –