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

标签 mysql sql

在电话系统场景中,我有 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/

相关文章:

php - 独立使用 Codeigniter DB_forge 类

java - 授予mysql所有用户权限?

mysql - Rails Resque 工作人员因 mysql "Too many connections"而失败

mysql - 灵活搜索错误 : missing values

python - SQLAlchemy select 语句执行随机挂起

c# - 运行存储过程时无法解释的超时

mySQL 从所有者历史记录中加入事务所有者

mysql - 使用多个 OR 语句更新

mysql - 当我使用 WHERE 调用 MySQL 中的 View 时会发生什么

SQL 不是单组组函数