Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter union result

I'm making select with union. select * from table_1 union select * from table_2 ...

Is it possible to filter query result by column values?

like image 221
gruber Avatar asked Oct 29 '10 10:10

gruber


1 Answers

Yes, you can enclose your entire union inside another select:

select * from (
select * from table_1 union select * from table_2) as t
where t.column = 'y'

You have to introduce the alias for the table ("as t"). Also, if the data from the tables is disjoint, you might want to consider switching to UNION ALL - UNION by itself works to eliminate duplicates in the result set. This is frequently not necessary.

like image 109
Damien_The_Unbeliever Avatar answered Oct 19 '22 18:10

Damien_The_Unbeliever