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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:18:48  来源:igfitidea点击:

WHERE statement after a UNION in SQL?

mysqlsql

提问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 UNIONin a sub-SELECTand apply the WHEREclause 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 UNIONis looking for two complete SELECTstatements to combine, and the WHEREclause is part of the SELECTstatement.

基本上, theUNION正在寻找SELECT要组合的两个完整语句,并且该WHERE子句是SELECT语句的一部分。

It may make more sense to apply the outer WHEREclause 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= ''