我在数据库中有奖励积分表:
customer_reward_id customer_id order_id points
1 1 3 20
2 1 4 40
3 1 5 30
4 1 6 30
5 1 7 40
收集100分(总和)并从表中删除
其中customer_id = customer_reward_id ASC的订单
任何想法?
答案 0 :(得分:1)
如果是关于删除100分以上(总结)的客户的记录。这是查询:
delete from rewards_points
where customer_id in (
SELECT customer_id
FROM (select * from `rewards_points`) dummy
group by customer_id
having sum(points)>=100);
注意:在MySQL中,您无法直接在from
子句中指定相同的表,您正在执行删除/更新操作。所以,在这个答案中,我添加了额外的子查询和给定的别名dummy
答案 1 :(得分:0)
在实际应用中,我们不会删除记录以从客户中扣除积分。因为报告和管理目的需要每个带有订单的记录。相反,从客户中扣除100分的最佳方法是添加带负号的点,然后总结所有点,以便获得最终值。
例如,执行以下操作:
插入负值的新记录。
insert into reward_points (customer_id,order_id,points) values (1,8,-100);
然后将总值汇总如下。
select sum(points) as total_rewards where customer_id=1;
这样您就可以保留以前订单的所有记录,也可以减少奖励。
希望这有助于满足您的要求。