Mysql嵌套左连接计数

时间:2013-09-27 16:35:11

标签: mysql

我有一组MySQL有三个表,有很多关系:交易,订单和优惠券。

Deals
|----|--------------|
| id |    title     |
|----|--------------|
|  1 | Some deal    |
|  2 | Another deal |
|----|--------------|

Orders
|----|---------|-----------|
| id | deal_id |   state   |
|----|---------|-----------|
|  1 |       1 | purchased |
|  2 |       1 | purchased |
|  3 |       1 | expired   |
|  4 |       2 | purchased |
|----|---------|-----------|

Coupons
|----|----------|
| id | order_id |
|----|----------|
|  1 |        1 |
|  2 |        1 |
|  3 |        1 |
|  4 |        2 |
|  5 |        2 |
|  6 |        4 |
|----|----------|

所以,交易有很多订单,有许多优惠券。

我想做的是在计算购买订单和优惠券的数量时选择交易表。

我知道如何计算付费订单:

SELECT deals.*, count(orders.id) AS orders_purchased_count FROM deals
LEFT JOIN orders ON deals.id=orders.deal_id AND orders.state='purchased'
WHERE deal_id < 3
GROUP BY deals.id

Deals
|----|--------------|------------------------|
| id |    title     | orders_purchased_count |
|----|--------------|------------------------|
|  1 | Some deal    |                      2 |
|  2 | Another deal |                      1 |
|----|--------------|------------------------|

同样,我可以获得订单优惠券的数量:

SELECT orders.*, count(coupons.id) AS coupons_count FROM orders
LEFT JOIN coupons ON orders.id=couoons.orders_id
WHERE orders.state='purchased'
GROUP BY orders.id

Orders
|----|-----------|---------------|
| id |   state   | coupons_count |
|----|-----------|---------------|
|  1 | purchased |             3 |
|  2 | purchased |             2 |
|  4 | purchased |             1 |
|----|-----------|---------------|

我的问题是:如何将这些组合起来,以便我可以在orders_purchased_count旁边添加coupons_count?

Deals
|----|--------------|------------------------|---------------|
| id |    title     | orders_purchased_count | coupons_count |
|----|--------------|------------------------|---------------|
|  1 | Some deal    |                      2 |             5 |
|  2 | Another deal |                      1 |             1 |
|----|--------------|------------------------|---------------|

在我的情况下,在加入WHERE deal_id < 3之前从deals进行选择时运行orders过滤器并在运行WHERE orders.state='purchased'过滤器时运行orders过滤器是件棘手的事情。在加入coupons之前从orders选择。它是一个大型数据集,我不想将所有coupons和{{1}}加载到内存中以便加入。

不知道如何做到这一点。

2 个答案:

答案 0 :(得分:3)

这有用吗?我无法理解你担心哪一部分会变得棘手。

SELECT deals.*, COUNT(DISTINCT(orders.id)) AS orders_purchased_count, COUNT(coupons.id) AS coupons_count
FROM deals
LEFT JOIN orders 
  ON deals.id=orders.deal_id
    AND orders.state='purchased' 
LEFT JOIN coupons
  ON orders.id=coupons.orders_id
WHERE deal_id < 3
GROUP BY deals.id;

答案 1 :(得分:0)

尝试使用co相关子查询并加入

SELECT deals.*, count(orders.id) AS orders_purchased_count 
(
SELECT  count(id) FROM coupons WHERE orders_id = orders.id 

) AS coupons_count 

FROM deals
LEFT JOIN orders ON deals.id=orders.deal_id AND orders.state='purchased'
WHERE deal_id < 3
GROUP BY deals.id