2013-05-16 57 views
0

下面是我的問題,任何一個有想法如何解決這個問題:MYSQL:如何使它在選擇查詢虛擬列?

實例查詢:

SELECT id, table2.id as global_id, table3.id as global_id 
FROM table1 
LEFT JOIN table2 
    ON (table1.id = table2.tab1_id) 
LEFT JOIN table3 
    ON (table1.id = table3.tab1_id) 
WHERE etc etc 

基本上我不想在select語句寫兩次「global_id」列,也在某些行中有id = NULL

您能否在這裏寫下工作查詢。我如何獲得global_id列中所有行的id值?

感謝

+0

使用'SELECT ... UNION ...' – Voitcus

回答

0

使用COALESCE

SELECT table1.id, COALESCE(table2.id, table3.id) as global_id 
FROM table1 
LEFT JOIN table2 
    ON (table1.id = table2.tab1_id) 
LEFT JOIN table3 
    ON (table1.id = table3.tab1_id) 
WHERE etc etc 
+0

COALESCE不工作的人 –

+0

嗨,對不起,我錯了它的工作很好你是搖滾人(y) –

+0

@VinodPatidar - 它確定,很高興它現在工作:) –

0

猜你需要這樣的:

SELECT id, table2.id as global_id 
FROM table1 
LEFT JOIN table2 
    ON (table1.id = table2.tab1_id) 
WHERE etc etc 
UNION ALL 
SELECT id, table3.id as global_id 
FROM table1 
LEFT JOIN table3 
    ON (table1.id = table3.tab1_id) 
WHERE etc etc 
+0

你的意思是我必須用UNION ALL寫每個查詢?不,但它不是解決方案對不起 –

+0

它不清楚你想要什麼,然後請澄清問題 – ZZa