使用UNION获取的数据数组的MySQL密钥名称

时间:2012-11-04 06:35:56

标签: mysql union

objects

id    name    is_animal
-----------------------
1     dog     1
2     cat     1
3     chair   0
4     rabbit  1

查询

(SELECT name AS animal_name FROM objects WHERE is_animal = 1)
UNION
(SELECT name AS object_name FROM objects WHERE is_animal = 0)

和结果

[animal_name] => dog
[animal_name] => cat
[animal_name] => rabbit
[animal_name] => chair    // expected: [object_name] => chair

我已经在第二个SELECT中使用了AS,为什么它会返回animal_name而不是object_name

2 个答案:

答案 0 :(得分:0)

UNION

(SELECT name AS animal_name,'' object_name FROM objects WHERE is_animal = 1)
UNION
(SELECT '' as animal_name, name AS object_name FROM objects WHERE is_animal = 0)

case

select case is_animal when 1 name else '' end as  animal_name,
       case is_animal when 0 name else '' end as  object_name
from objects

答案 1 :(得分:0)

在UNION查询中,始终选择第一个SELECT的列名作为最终结果视图的列名。如果每个SELECT的相应列名不同,您如何期望列名最终?在UNION查询的后续SELECT中甚至不提及列名是合适的,因为它没有添加任何含义。

documentation MySQL使用相同的

(SELECT 1 AS sort_col, col1a, col1b, ... FROM t1)
UNION
(SELECT 2, col2a, col2b, ... FROM t2) ORDER BY sort_col, col1a;