2014-10-11 71 views
0

我從兩個不同的表中選擇相同的列,但想要使用select as來使它們具有不同的名稱。MySQL - 從兩個不同的表重命名具有相同名稱的選定列

(SELECT letter AS letter_1, sex AS sex_1 FROM `celebs_a` LIMIT 1) 
UNION 
(SELECT letter AS letter_2, sex AS sex_2 FROM `celebs_b` LIMIT 1) 

該查詢返回此:

letter_1 sex_1 
a  1 
b  1 

但是,我想它返回此:

letter_1 letter_2 sex_1 sex_2 
a  b  1  1 

我怎樣才能讓該查詢返回的每個值作爲不同的列名?謝謝。

回答

1
SELECT MAX(letter_1) AS letter_1, MAX(sex_1) AS sex_1, 
     MAX(letter_2) AS letter_2, MAX(sex_2) AS sex_2 
FROM (
    (SELECT letter AS letter_1, '' AS letter_2, sex AS sex_1, 0 AS sex_2 
    FROM celebs_a 
    LIMIT 1) 
    UNION 
    (SELECT '' AS letter_1, letter AS letter_2, 0 AS sex_1, sex AS sex_2 
    FROM celebs_b 
    LIMIT 1) 
) AS derived_table_must_have_an_alias 

您可以輕鬆地擴展這個到從每個表中選擇多個列。只需將0''作爲另一個表中這些列的佔位符。

+0

我跑了那個查詢,但得到這個錯誤:#1248 - 每個派生表必須有它自己的別名 – Graham 2014-10-11 01:57:00

+0

固定在更新中。 – Barmar 2014-10-11 01:57:39

+0

現在說:#1054 - '字段列表'中的未知列'0AS' – Graham 2014-10-11 02:03:08

1

試試這個:

SELECT 
    (SELECT letter AS letter_1 FROM `celebs_a` LIMIT 1) AS letter_1, 
    (SELECT letter AS letter_2 FROM `celebs_b` LIMIT 1) AS letter_2; 

更新時間:

SELECT 
    (SELECT letter ... FROM celebs_a ...) AS letter_1, 
    (SELECT letter ... FROM celebs_b ...) AS letter_2, 
    (SELECT sex ... FROM celebs_a ...) AS sex_1, 
    (SELECT sex ... FROM celebs_b ...) AS sex_2 

或者Barmars的做法會更好(這僅運行2 SELECT查詢)

+0

嘿,工作!你能修改你的答案嗎?我想從每個表中選擇2列。有沒有辦法做到這一點,我不需要做一堆選擇語句?最終,我要從每張桌子拉出大約20列。 – Graham 2014-10-11 01:46:58

+0

@Graham更新;) – 2014-10-11 01:54:00

相關問題