如果不在第二个表中,MySQL join想要排除行

时间:2014-06-28 11:37:34

标签: mysql left-join right-join

我真的很伤心,并希望得到一些帮助; - )

我有这个MySQL查询:

SELECT
    sum(ot.value) AS total_value,
    avg(ot.value) AS avg,
    count(ot.value) AS count
FROM
    orders_total ot,
    orders o
WHERE
    ot.orders_id = o.orders_id
AND ot.class = 'ot_total'
AND o.customers_name != 'Test Test'
AND o.date_purchased >= '2014-02-01T00:00:00'
AND o.date_purchased < '2014-03-01T00:00:00'

但我只想在订单和orders_total表中订购order_id时选择值。

因此,如果orders_total表中缺少orders_id,我不希望它包含在查询中..

我尝试左右连接,如下所示,没有任何运气; - (

SELECT
    sum(ot.value) AS total_value,
    avg(ot.value) AS avg,
    count(ot.value) AS count
FROM
    orders o
RIGHT JOIN orders_total ot ON (ot.orders_id = o.orders_id)
WHERE
    ot.orders_id = o.orders_id
AND ot.class = 'ot_total'
AND o.customers_name != 'Test Test'
AND o.date_purchased >= '2014-02-01T00:00:00'
AND o.date_purchased < '2014-03-01T00:00:00'

我做错了什么?

提前致谢! BAS

2 个答案:

答案 0 :(得分:0)

试试这个..内部JOIN做你想做的事情。

 SELECT
        sum(ot.value) AS total_value,
        avg(ot.value) AS avg,
        count(ot.value) AS count
    FROM
        orders o
    INNER JOIN orders_total ot ON (ot.orders_id = o.orders_id)
    WHERE
    AND ot.class = 'ot_total'
    AND o.customers_name != 'Test Test'
    AND o.date_purchased >= '2014-02-01T00:00:00'
    AND o.date_purchased < '2014-03-01T00:00:00'

答案 1 :(得分:0)

说实话,我不认为这是join问题。我认为你得到了错误的结果,认为这是一个加入问题。您的数据可能会使结果倍增。也许你真的想要:

SELECT sum(ot.value) AS total_value,
       avg(ot.value) AS avg,
       count(ot.value) AS count
FROM orders_total ot
WHERE ot.class = 'ot_total' AND
      EXISTS (select 1
              from orders o
              where ot.orders_id = o.orders_id and 
                    o.customers_name <> 'Test Test' and
                    o.date_purchased >= '2014-02-01T00:00:00' and
                    o.date_purchased < '2014-03-01T00:00:00'
            );

我这样说是因为您的select仅使用orders_total表中的列。这会带来价值因连接而成倍增加的风险。