开发者

Using a single common WHERE condition for UNION in SQL

开发者 https://www.devze.com 2023-01-05 04:17 出处:网络
I am trying to do something like this: SELECT a.date AS EnrollDate, a.id, a.name, b.address FROM student开发者_如何学JAVA a JOIN Location b ON a.id=b.id

I am trying to do something like this:

SELECT a.date AS EnrollDate, a.id, a.name, b.address FROM student开发者_如何学JAVA a JOIN Location b ON a.id=b.id  
UNION  
SELECT a.date AS EnrollDate, a.id, a.name, b.address FROM teacher a JOIN Location b ON a.id=b.id  
WHERE a.date>'2010-01-01'  
ORDER BY EnrollDate

But the WHERE condition applies to the second SELECT statement only. I need to somehow apply to both the SELECT. The only option I have now is to apply WHERE condition individually. But I am working with several UNIONs and it is kind of tedious to include WHERE in all the places. I was wondering if there is an easy way out.

By the way, I am working with MySQL.


SELECT * FROM (
    SELECT a.date AS EnrollDate, a.id, a.name, b.address FROM student a 
    JOIN Location b ON a.id=b.id  
    UNION  
    SELECT a.date AS EnrollDate, a.id, a.name, b.address FROM teacher a 
    JOIN Location b ON a.id=b.id  
) A
WHERE EnrollDate > '2010-01-01'  
ORDER BY EnrollDate

This also has the advantage, compared to individual ORDER BY's that the whole result is correctly ordered.


Have you tried something like:

SELECT * FROM 
(
    SELECT a.date AS EnrollDate, a.id, a.name, b.address FROM student a JOIN Location b ON a.id=b.id  
    UNION  
    SELECT a.date AS EnrollDate, a.id, a.name, b.address FROM teacher a JOIN Location b ON a.id=b.id 
) A
    WHERE a.date>'2010-01-01'  
    ORDER BY EnrollDate


There is no way around it, you have to repeat the WHERE for each individual select clause.

0

精彩评论

暂无评论...
验证码 换一张
取 消