tags:

views:

59

answers:

5

I am trying to do something like this:

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  
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.

A: 

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

Frank
Ok, looking at the other answers, my answer is wrong as it states there is no way around it. However, from a performance point of view, I would assume all the solutions of first UNIONing and then evaluating the WHERE condition will probably be worse (if you do not have a really clever optimizer, which I would not assume for MySql).
Frank
+2  A: 

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
Hal
You have to either give the subquery an alias or replace the 'a.date' with simply 'date'.
inflagranti
yeah, i forgot. fixed it in the edit
Hal
A: 

You could select into a temporary table, then select from the temporary table with the where clause.

Oded
Why the downvote?
Oded
+3  A: 
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  
)
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.

inflagranti
Well, same answer :P good work mate
Hal
Thanks mate. You solved my problem :)
curious
By the way, the WHERE clause should use EnrollDate instead of a.date for comparison ;)
curious
Very true, fixed that!
inflagranti
A: 

Another change is rather than joing location table with two table , Union student and teacher table in one query and than do the join with location table and than apply your where condition

select * from 
(
 select EnrollDate,ID,Name,Address from Location
 inner join 
 (
   SELECT a.date AS EnrollDate, a.id as Id, a.name as Name FROM student 
   union
   SELECT a.date AS EnrollDate, a.id as Id, a.name as Name FROM teacher 
 ) d on 
 d.id=Location.id
) WHERE EnrollDate >'2010-01-01'   
ORDER BY EnrollDate 
Pranay Rana