gpt4 book ai didi

MYSQL UPDATE 行匹配基于变量的条件

转载 作者:行者123 更新时间:2023-11-29 23:19:43 25 4
gpt4 key购买 nike

在电话系统场景中,我有 2 个表。

  • table1 由以下内容组成:customer_idcall_durationcalldateskip_billing
  • table2 由以下部分组成:customer_idbonus_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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com