0

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

我有这个 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_id 同时在 orders 和 orders_total 表中时选择这些值。

因此,如果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'

我究竟做错了什么?

提前致谢!巴斯

4

2 回答 2

0

试试这个..Inner 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'
于 2014-06-28T11:38:59.363 回答
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。这会冒着由于连接而使值成倍增加的风险。

于 2014-06-28T13:15:49.873 回答