1

这是问我问题的简化表:

      Names
+------+----------+
|  id  |   name   |
|------+----------|
|  1   |  Alex    |
|      |          |
|  2   |  John    |
|      |          |
|  3   |  Fred    |
|      |          |
|  4   |  Andy    |
+------+----------+

id: primary key

如何只执行一个查询并获取两个名称?我有两个 ID n1n2我想检索两个对应的名称:

SELECT name1, name2 FROM names WHERE ...n1....n2...

执行查询后,n1=2结果n2=3应该是:

+------------+------------+
|   name1    |   name2    |
+------------+------------+
|   John     |   Fred     |
+------------+------------+

可能吗?我不知道。

4

5 回答 5

7

您可以将聚合函数与 CASE 表达式一起使用:

select
  max(case when id = 2 then name end) Name1,
  max(case when id = 3 then name end) Name2
from names;

演示

于 2013-07-10T17:33:07.753 回答
5

直截了当,虽然必须执行两个子选择:

SELECT
(SELECT Name FROM Names WHERE ID = 2) as Name1,
(SELECT Name FROM Names WHERE ID = 3) as Name2
于 2013-07-10T17:28:47.247 回答
2

SELECT (SELECT Name FROM names WHERE ID =1 ), (SELECT Name FROM Names WHERE ID = 2) FROM DUAL

于 2013-07-10T17:32:52.820 回答
0

毫米我希望我理解似乎很简单:

SELECT `name` FROM `names` WHERE `id` = '1' OR `id` = '2' LIMIT 2
于 2013-07-10T17:36:48.307 回答
0

您可以使用子选择:
SELECT (SELECT nameFROM NamesWHERE id=1) AS name1, (SELECT nameFROM NamesWHERE id=2) ASname2

于 2013-07-10T17:31:22.383 回答