How do I apply a WHERE statement after a UNION in SQL/MySQL?
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: SELECT * FROM (SELECT * FROM TableA UNION SELECT * FROM TableB ) AS U WHERE U.
You can simple GROUP BY in both tables and then union. But then you'll need another group by anyway, to unite any grouped row from the first table to the one in the second.
Here is the query to count on the union query. mysql> select count(*) as UnionCount from -> ( -> select distinct UserId from union_Table1 -> union -> select distinct UserId from union_Table2 -> )tbl1; The following is the output displaying the count.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With