2010-06-29 17 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