[mysql] WHERE statement after a UNION in SQL?

How do I apply a WHERE statement after a UNION in SQL/MySQL?

This question is related to mysql sql

The answer is


select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''

You probably need to wrap the UNION in a sub-SELECT and apply the WHERE clause afterward:

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.

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.