2

我有一组 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选择时运行过滤器,并在我加入之前选择时运行过滤器。这是一个大型数据集,我不想为了加入而将所有数据加载到内存中。dealsordersWHERE orders.state='purchased'orderscouponsorderscoupons

不知如何做到这一点。

4

2 回答 2

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;
于 2013-09-27T17:09:01.433 回答
0

试试这个与共同相关的子查询并加入

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
于 2013-09-27T17:05:22.500 回答