两个结果在一个查询中

时间:2013-07-10 17:26:09

标签: php mysql sql

这是提出问题的简化表:

      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=2n2=3的查询后,结果应为:

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

有可能吗?我不知道。

5 个答案:

答案 0 :(得分:7)

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

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

请参阅Demo

答案 1 :(得分:5)

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

SELECT
(SELECT Name FROM Names WHERE ID = 2) as Name1,
(SELECT Name FROM Names WHERE ID = 3) as Name2

答案 2 :(得分:1)

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

答案 3 :(得分:0)

您可以使用子选择:
    SELECT(SELECT name FROM Names WHERE id = 1)AS name1,(SELECT name FROM Names WHERE id = 2)AS name2

答案 4 :(得分:0)

我希望我理解这似乎很简单:

SELECT `name` FROM `names` WHERE `id` = '1' OR `id` = '2' LIMIT 2