在SQL中为UNION使用单个公共WHERE条件

时间:2010-07-01 10:24:53

标签: sql mysql

我正在尝试做这样的事情:

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

但WHERE条件仅适用于第二个SELECT语句。我需要以某种方式应用于SELECT。我现在唯一的选择是单独应用WHERE条件。但我正在与几个UNION合作,在所有地方都包含WHERE是很乏味的。 我想知道是否有一个简单的出路。

顺便说一下,我正在使用MySQL。

3 个答案:

答案 0 :(得分:13)

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

与单个ORDER BY相比,这也有利于整个结果的正确排序。

答案 1 :(得分:4)

你有没有试过像:

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

答案 2 :(得分:-1)

没有办法绕过它,你必须为每个单独的select子句重复WHERE。