MYSQL UNION和在哪里条件

时间:2013-03-11 06:59:40

标签: mysql union where

我无法在MYSQL中为UNION添加WHERE条件。 现在使用下面的SQL行,我将获取表中的所有记录,而不是在2个日期之间过滤日期。

我的订单工作正常。我想在不创建视图的情况下这样做

    SELECT *
    FROM DCHDR AS H
    LEFT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos
    UNION
    SELECT *
    FROM DCHDR AS H
    RIGHT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos
    WHERE H.DC_date
    BETWEEN '2013-03-02'
    AND '2013-03-11'
    ORDER BY `Product_Desc` ASC
    LIMIT 510 , 30

3 个答案:

答案 0 :(得分:4)

ORDER BY不同,联合中的WHERE子句仅影响联合的那一部分(它附加的单SELECT个查询),而整个联盟。

将你的联合放在子查询中并过滤结果:

SELECT *
FROM
(
    SELECT *
    FROM DCHDR AS H
    LEFT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos
    UNION
    SELECT *
    FROM DCHDR AS H
    RIGHT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos
) H
WHERE H.DC_date BETWEEN '2013-03-02' AND '2013-03-11'
ORDER BY `Product_Desc` ASC
LIMIT 510, 30

或复制每个部分的条件:

SELECT *
FROM DCHDR AS H
LEFT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos
WHERE H.DC_date BETWEEN '2013-03-02' AND '2013-03-11'
UNION
SELECT *
FROM DCHDR AS H
RIGHT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos
WHERE H.DC_date BETWEEN '2013-03-02' AND '2013-03-11'
ORDER BY `Product_Desc` ASC
LIMIT 510 , 30

看起来你正试图模拟一个完整的连接。我可能会建议以下查询,它应该更多更快(并且实际做你想做的事情) ,过滤联盟的第二部分):

SELECT *
FROM DCHDR AS H
LEFT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos
WHERE H.DC_date BETWEEN '2013-03-02' AND '2013-03-11'
UNION ALL
SELECT *
FROM DCHDR AS H
RIGHT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos
WHERE H.DC_No IS NULL
ORDER BY `Product_Desc` ASC
LIMIT 510 , 30

请注意,如果DCDTL中有重复的行,您有意尝试使用UNION进行过滤,则可以将UNION ALL更改为UNION,但我怀疑这一点实际上不是的情况。

答案 1 :(得分:2)

尝试将其放入子查询中并在外部查询中进行过滤:

SELECT *
FROM
(
    SELECT *
    FROM DCHDR AS H
    LEFT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos
    UNION
    SELECT *
    FROM DCHDR AS H
    RIGHT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos
) AS sub
WHERE DC_date BETWEEN '2013-03-02'
                  AND '2013-03-11'
ORDER BY `Product_Desc` ASC;
LIMIT 510 , 30

答案 2 :(得分:0)

让我们看看你的UNION。它由两部分组成:

SELECT *
FROM DCHDR AS H
LEFT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos

SELECT *
FROM DCHDR AS H
RIGHT JOIN DCDTL AS T ON H.DC_No = T.DC_Nos
WHERE H.DC_date
BETWEEN '2013-03-02'
AND '2013-03-11'

UNION中的条件适用于后一部分。第二部分只是一个INNER JOIN,因为你在左侧部分列上有一个条件。由于UNION删除了重复的行,因此总查询等于您的第一个LEFT JOIN