MySQL SQL 中 UNION 之后的 WHERE 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5452233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WHERE statement after a UNION in SQL?
提问by einstein
How do I apply a WHERE statement after a UNION in SQL/MySQL?
如何在 SQL/MySQL 中的 UNION 之后应用 WHERE 语句?
回答by Jonathan Leffler
If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:
如果要将 WHERE 子句应用于 UNION 的结果,则必须在 FROM 子句中嵌入 UNION:
SELECT *
FROM (SELECT * FROM TableA
UNION
SELECT * FROM TableB
) AS U
WHERE U.Col1 = ...
I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.
我假设 TableA 和 TableB 是联合兼容的。当然,您也可以将 WHERE 子句应用于 UNION 中的每个单独的 SELECT 语句。
回答by David
You probably need to wrap the UNION
in a sub-SELECT
and apply the WHERE
clause afterward:
您可能需要将 the 包装UNION
在 sub- 中,SELECT
然后再应用该WHERE
子句:
SELECT * FROM (
SELECT * FROM Table1 WHERE Field1 = Value1
UNION
SELECT * FROM Table2 WHERE Field1 = Value2
) AS t WHERE Field2 = Value3
Basically, the UNION
is looking for two complete SELECT
statements to combine, and the WHERE
clause is part of the SELECT
statement.
基本上, theUNION
正在寻找SELECT
要组合的两个完整语句,并且该WHERE
子句是SELECT
语句的一部分。
It may make more sense to apply the outer WHERE
clause to both of the inner queries. You'll probably want to benchmark the performance of both approaches and see which works better for you.
将外部WHERE
子句应用于两个内部查询可能更有意义。您可能希望对两种方法的性能进行基准测试,看看哪种方法更适合您。
回答by pinkykitty
select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''