1

桌子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

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

4

2 回答 2

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
于 2012-11-04T07:25:47.613 回答
0

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

文档MySQL 使用相同的

(SELECT 1 AS sort_col, col1a, col1b, ... FROM t1)
UNION
(SELECT 2, col2a, col2b, ... FROM t2) ORDER BY sort_col, col1a;
于 2012-11-04T07:26:26.577 回答