2010-06-29 15 views
0

我試圖做一個SELECT,我需要用一個柱至極選擇指定的表定義對象的類型:使用如果在MySQL查詢

table_buildings 
id  name    location  source_type  source_id 
1  NY Appartament  New York  0    NULL 
2  Guggenheim Museum Manhattan  1    27 
3  MoMA    New York  2    3 

table_url // source type == 1 
id  name    url 
27  Guggenheim Site http://www.guggenheim.org/ 

table_books // source type == 2 
id  name    pages   sample   author 
3  World Museums  125-127   path/img.jpg John Smith 

我不知道這是否是可能的,但我有一些問題要解決它沒有我的查詢中的IF語句,因爲我可以通過table_buildings

source_type列找到合適的表確實存在軀體tecnique使用的IF一個SELECT查詢裏面?

+1

請根據提供的數據提供您期望得到結果的例子。 – 2010-06-29 16:58:56

回答

2

我只是加入這兩個表,並使用COALESCE爲連接表中的重複列名稱。

SELECT COALESCE(table_url.name, table_books.name) as name, url, pages, sample author FROM table_buildings 
LEFT OUTER JOIN table_url ON table_buildings.source_type = 1 AND table_buildings.source_id = table_url.id 
LEFT OUTER JOIN table_books ON table_buildings.source_type = 2 AND table_buildings.source_id = table_books .id 
+0

我發現它非常易於使用!謝謝 – vitto 2010-06-29 17:31:47

1

恐怕唯一可行的方法是無條件地從所有表中選擇。雖然沒有多少開銷。
只需要根據需要連接儘可能多的表格。沒有相應信息的只會返回空值。

+0

感謝您的信息,我會記住它,我認爲這是因爲性能問題。 – vitto 2010-06-29 17:40:08

0

你可以UNION三個不同SELECT s那JOINWHERE條款的三個表。

或者,您可以在一個查詢中針對所有三個表加入,並使用CASE運算符從基於source_type的適當連接表中選擇一列。

0

您可以在SELECT中使用「CASE WHEN」。

SELECT 
table_buildings.id, 
table_buildings.name, 
table_buildings.location, 
CASE WHEN table_buildings.source_type = 0 
    THEN "" 
    ELSE CASE WHEN table_buildings.source_type = 1 
    THEN table_url.name 
    ELSE table_books.name 
    END CASE 
    END CASE AS source_name 
FROM table_buildings 
LEFT JOIN table_url 
ON table_buildings.source_id = table_url.id 
LEFT JOIN table_books 
ON table_buildings.source_id = table_books.id