我正在尝试查明使用折扣代码的用户是否在首次订单后下订单。
这三个表是:order
、user
、coupon_uses
从 coupon_uses
中,我检索的唯一数据是通过以下方式使用代码的用户:
SELECT *
FROM coupon_uses
WHERE coupon_id = 21921
我会得到一个返回的表格,其中包含用户 ID、订单 ID 和他们使用的优惠券。
ID Coupon_ID User_ID Order_ID
11 21921 148871 1448181
21 21921 888381 1448191
31 21921 888411 1448201
41 21921 354311 1448211
51 21921 452671 1448221
61 21921 684791 1448231
现在,我需要检查第一个查询中返回的用户(使用该代码的用户)与整个 order
表:
我尝试过这样的事情:
SELECT order.user_id,
COUNT(*) AS Total_Orders
FROM `order`
WHERE `order`.user_id = (
SELECT user_id
FROM coupon_uses
WHERE coupon_id = 21921)
AND order.order_status != "Cancelled"
GROUP BY order.user_id ASC
ORDER BY `order`.orderplaced_ts
但是我收到子查询返回超过 1 行的信息。
期望的结果是返回用户 ID 列表,其中包含他们下的订单总数和订单日期。
User_ID Total_Orders Last_Order
148871 17 2015_01_01
888381 19 2015_01_01
888411 3 2015_01_14
354311 5 2015_05_01
452671 99 2015_02_01
684791 213 2015_01_05
谢谢。
最佳答案
试试这个:
SELECT o.user_id, COUNT(*) AS total_orders
FROM order AS o
INNER JOIN coupon_uses AS c ON o.user_id = c.user_id
WHERE c.coupon_id = 21921
GROUP BY o.user_id
ORDER BY MIN(o.orderplaced_ts)
这假设用户只能使用优惠券一次。
关于MYSQL 查询用户是否使用特定优惠券代码下订单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33223472/