在电话系统场景中,我有 2 个表。
- table1 由以下内容组成:
customer_id
、call_duration
、calldate
、skip_billing
。 - table2 由以下部分组成:
customer_id
、bonus_seconds
。
表1存储所有客户的所有调用,表2存储bonus_seconds,它表示定义的客户允许的免费通话时间(即:对于客户1,前40累计秒是免费的)。
我必须根据下面解释的条件编写一个查询来更新 table1: 在表2中免费定义的调用中设置skip_billing。
因此,我首先需要按 customer_id 进行分组,然后迭代调用,在 call_duration 上增加累积变量(cumsec)并相应地设置skip_billing。
表1示例是:
|customer_id |billsec | skipbill|
|1 |12 | 0 |
|1 |10 | 0 |
|1 |15 | 0 |
|1 |8 | 0 | <--need to set 1 due to cumsec=45 for customer_id=1
|2 |12 | 0 | <--nop
|3 |12 | 0 | <--nop
|2 |12 | 0 | <--need to set 1 due to cumsec=24 for customer_id=2
|1 |12 | 0 | <--need to set 1 ....
|3 |15 | 0 | <--need to set 1 due to cumsec=27 for customer_id=3
|customer_id |bonus_seconds|
|1 |40 |
|2 |20 |
|3 |15 |
如何在 SQL 中编写查询或过程来实现此行为? 非常感谢
最佳答案
假设表有一个主键 = id 你可以尝试:
SET SQL_SAFE_UPDATES=0;
update table table1
join (select id, sum(billsec) s from table
group by id having sum(billsec) < 1000) t1
on (t1.id = table1.id)
set table1.skipbill = 1
关于MYSQL UPDATE 行匹配基于变量的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27430576/