MySQL:按列合并3个查询结果

时间:2016-03-04 15:41:52

标签: mysql sql

我有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    |

第三个查询返回:

| 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

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

until [[ "$(ifconfig)" =~ $t2 ]]; do
    sleep 1
done

答案 1 :(得分:-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