2016-03-04 78 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个查询结果。 –