Php 在mySQL查询中使用IF
我正在尝试创建一个Php 在mySQL查询中使用IF,php,mysql,if-statement,Php,Mysql,If Statement,我正在尝试创建一个SELECT,其中我需要通过定义主题类型的列选择一个指定的表: table_buildings id name location source_type source_id 1 NY Appartament New York 0 NULL 2 Guggenheim Museum Manhattan 1 2
SELECT
,其中我需要通过定义主题类型的列选择一个指定的表:
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\u buildings的source\u type
列找到正确的表
是否存在在选择查询中使用IF
的技术?恐怕唯一可能的方法是无条件地从所有表中选择。不过开销不大。
只需左键即可根据需要连接多个表。没有相应信息的表只返回空值。恐怕唯一可能的方法是无条件地从所有表中选择。不过开销不大。
只需左键即可根据需要连接多个表。没有相应信息的将只返回空值。您可以UNION
选择三个不同的将连接到带有WHERE
子句的三个表中
或者,您可以在一个查询中对所有三个表进行联接,并使用CASE
操作符根据源类型
从相应的联接表中选择一列。您可以联合
三个不同的选择联接
到具有WHERE
子句的三个表
或者,您可以在一个查询中对所有三个表进行联接,并使用CASE
运算符根据source\u type从相应的联接表中选择一列。您可以在选择中使用“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
您可以在选择中使用“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
我只需连接两个表,并在连接的表中使用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
我只需连接两个表,并在连接的表中使用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
请提供一个基于所提供数据的结果预期示例。请提供一个基于所提供数据的结果预期示例。我发现它非常容易使用!谢谢,我发现它很容易使用!谢谢你提供的信息,我会记住的,我之所以这样想是因为性能问题。谢谢你提供的信息,我会记住的,我之所以这样想是因为性能问题。