MySQL查询按类型计算用户订单

时间:2017-12-13 14:14:59

标签: mysql

我有3个表:users,orders和order_item。

当用户可以订购时,订单商品只能是活动,仅限会员或两者,因此2行将被写入order_items

用户表

id | user_id   | name  | phone
---|-----------|-------|------
1  | 123456789 | Jon   | 555-55555
2  | 123456780 | Alice | 555-6666

订购表

id | user_id | user_uid  | user_info
---|---------|-----------|----------
1  | 1       | 123456789 | bla
2  | 2       | 123456780 | foo
3  | 2       | 123456780 | foo

order_items表

id  | order_id | order_type | price
--- | -------- | ---------- | ------
1   | 1        | membership | 70
2   | 1        | event      | 200
3   | 2        | event      | 300
4   | 3        | membership | 70

这种关系是这样的,

order_items.order_id -> orders.id
orders.user_id -> users.id
orders.user_uid -> users.user_id

我正在寻找能产生这种输出的查询,

user_id   | name   | count_membership   | count_events   | total_orders
--------  | ------ | ------------------ | -------------- | --------------
123456789 | Jon    | 1                  | 1              | 1
123456780 | Alice  | 1                  | 1              | 2

我喜欢计算用户拥有的总订单数,并计算他拥有的每件商品的数量。最后,我想过滤掉count_membership = 0

所有用户

提前致谢,

2 个答案:

答案 0 :(得分:1)

您的查询需要在其公共字段上加入三个表,即user_id和order_id。

由于您说您不希望任何结果,其中成员资格不是订单类型,您的结果示例没有意义,并且使用单个mysql查询分组为单个结果会使事情变得复杂将order_type(单个字段)放入两个单独的列中。所以我稍微调整了一下。

select users.user_id, users.name, order_type, count(order_id) as total_orders from orders, order_items, users where users.user_id = orders.user_id and orders.id = order_items.order_id and order_type = "membership" group by users.user_id, users.name

mysql终端的工作输出:

mysql> select users.user_id, users.name, order_type, count(order_id) as total_orders from orders, order_items, users where users.user_id = orders.user_id and orders.id = order_items.order_id and order_type = "membership" group by users.user_id, users.name; +---------+------+------------+--------------+ | user_id | name | order_type | total_orders | +---------+------+------------+--------------+ | 123 | Jon | membership | 1 | | 1234 | Pam | membership | 2 | +---------+------+------------+--------------+

答案 1 :(得分:1)

您可以使用某些条件聚合

来获得预期的结果集
select u.user_id,
u.name,
sum(oi.membership_count) membership_count,
sum(oi.event_count) event_count,
count(o.id) total_orders
from users u
join orders o on u.id = o.user_id
join (
  select order_id,
  sum(order_type = 'membership') membership_count,
  sum(order_type = 'event') event_count
  from order_items 
  group by order_id
) oi on o.id = oi.order_id
group by u.user_id,u.name

Demo