3

我无法在 MYSQL 中为 UNION 设置 WHERE 条件。现在使用下面的 SQL 行,我得到了表中的所有记录,而不是过滤两个日期之间的日期。

我的订单工作正常。我想在不创建视图的情况下执行此操作

    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
4

3 回答 3

5

与 不同的是ORDER BYWHERE联合中的子句仅影响联合的那一部分(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 ALLUNION,但我怀疑实际上并非如此。

于 2013-03-11T07:02:35.877 回答
3

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

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
于 2013-03-11T07:02:27.547 回答
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'

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

于 2013-03-11T07:36:29.457 回答