2012-11-04 51 views
1

objectsMySQL數據數組的鍵名獲取與UNION

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

+0

你想要兩個不同的領域(animal_name/OBJECT_NAME)? –

+0

@Grisha是的,椅子應該有一個關鍵名'object_name'和其他人'animal_name' – user1643156

回答

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 
+0

明白了,謝謝。 – user1643156

+0

不客氣。 –

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; 
+0

永遠不知道「總是選擇第一個SELECT的列名作爲列名」。感謝您的信息,nawfal。 – user1643156