我有一份加入5个表的报告:
1 - 优惠券使用:id - coupon_id - user_id - order_id
2 - 优惠券:id - code - discount_type - discount_amount
3 - 订单:id - user_id - orderread_ts - order_status
4 - 付款:id - user_id - order_id - sub - tax - discount - total - payment_collected
5 - 用户:id - email - fname - lname
所以我运行的报告包含多个条件:促销名称,用户电子邮件,开始日期,结束日期。
这是我的问题:
SELECT
`Coupon`.`code` AS Promotion,
CONCAT('',o.`id`,'') AS Order_ID,
o.`orderread_ts` AS Order_Date,
u.`email` AS Customer_Email,
CONCAT(u.`fname`, " " ,u.`lname`) AS Name,
p.`subtotal` AS Subtotal,
p.`discount` AS Discount,
p.`total` AS Total
FROM `Coupon`
LEFT JOIN `Coupon_Uses` AS cu ON cu.`coupon_id` = `Coupon`.`id`
LEFT JOIN `Order` AS o ON o.`id` = cu.`order_id`
LEFT JOIN `User` AS u ON u.`id` = o.`user_id`
LEFT JOIN `Payments` AS p ON p.`id` = o.`id`
WHERE `Coupon`.`code` = 'email10'
AND o.`orderread_ts` > 0
AND o.`order_status` = ''
AND p.`discount` > 0
AND p.`payment_collected` = '1'
GROUP BY o.`id`
我得到了正确的结果,但是,如果在结帐时,销售没有完成(付款不当,错误的cc条目等),表Coupon Uses
将有两个条目同样的Order_id
。
现在,订单在计算时将显示不正确的信息。
我无法弄清楚如何从order_id
表中获得明确的coupon_uses
。
更新的最终查询
SELECT
c.`code` AS Promotion,
o.`id` AS Order_ID,
o.`orderread_ts` AS Order_Date,
u.`email` AS Customer_Email,
CONCAT(u.`fname`, " " ,u.`lname`) AS Name,
p.`subtotal` AS Subtotal,
p.`discount` AS Discount,
p.`total` AS Total
FROM `Coupon` c
INNER JOIN (SELECT DISTINCT coupon_id, user_id, order_id
FROM `Coupon_Uses`) AS cu ON cu.coupon_id = c.id
INNER JOIN `Order` AS o
ON o.`id` = cu.`order_id`
INNER JOIN `User` AS u
ON u.`id` = cu.`user_id`
INNER JOIN `Payments` AS p
ON p.`order_id` = cu.`order_id`
WHERE c.`code` = 'email10'
AND o.`orderread_ts` > 0
AND o.`order_status` = ''
AND p.`discount` > 0
AND p.`payment_collected` = '1'
首先更改我在第一次加入中使用SELECT DISTINCT
的内容,以确保我只获得唯一值。我在coupon_uses
的字段上加入了彼此的表格,我在最后一次加入时的语法错误,现在已经修复了。
性能:受影响的683行,耗时30.1ms
答案 0 :(得分:2)
如果我理解正确,您可能会遇到 Coupon_Uses 表中有两条记录的情况,这两条记录的 id 值不同。 coupon_id,user_id,order_id 可以是相同的......
如果是这样,我真的建议调查一下,因为它看起来不对。您是否可以在交易期间在另一个表中写入这样的重复记录,这样您可以确保没有这样的重复记录?或者,您是否可以添加状态列,以便临时记录获得草稿状态,而所有其他记录最终?
无论如何,如果是这种情况,您可以在查询中按如下方式解决:
替换:
LEFT JOIN `Coupon_Uses` AS cu ON cu.`coupon_id` = `Coupon`.`id`
使用:
LEFT JOIN (SELECT DISTINCT coupon_id, user_id, order_id
FROM `Coupon_Uses`) AS cu ON cu.`coupon_id` = `Coupon`.`id`
但这可能会对性能产生影响,因为连接可能无法从使用索引中受益。