小编典典

SQL:从复杂选择中进行更新

sql

在电话系统中,我有2张表。

  • table1是由组成:customer_idcall_durationcalldateskip_billing
  • table2由以下元素组成:customer_idbonus_seconds

table1存储所有客户的所有呼叫,而table2存储Bonus_seconds,代表代表已定义客户的免费通话时间(即:对于客户1,头40秒钟是免费的)。

我必须根据以下说明的条件编写查询以更新table1:在table2中定义为free的调用中设置skip_billing。

因此,我首先需要按customer_id分组,然后遍历调用,在call_duration上增加一个累积变量(cumsec),并相应地设置skip_billing。

table1的示例是:

|sqlid |customer_id |billsec | skipbill|
|0     |1           |12      | 1       |<--need to set 1 due to cume=12 for customer_id=1
|1     |1           |10      | 1       |<--need to set 1 due to cume=22 for customer_id=1
|2     |1           |15      | 1       |<--need to set 1 due to cume=37 for customer_id=1
|3     |1           |8       | 0       |<--nop(no operation) due to cume=45
|4     |2           |12      | 1       |<--need to set 1 due to cume=12 for customer_id=2
|5     |3           |12      | 1       |<--need to set 1 due to cume=12 for customer_id=3
|6     |2           |12      | 0       |<--nop due to cume=24 for customer_id=2
|7     |1           |12      | 0       |<--nop due to cume=49 for customer_id=1
|8     |3           |15      | 0       |<--nop due to cumsec=27 for customer_id=3

|customer_id |bonus_seconds|
|1           |40           |
|2           |20           |
|3           |15           |

我尝试使用这样的查询(感谢Gordon Linoff)返回了正确的行集:

    SELECT t.cume, t.calldate, t.customer_id FROM (SELECT t.*, (@cume := @cume + billsec) AS cume FROM table1 t CROSS JOIN (SELECT @cume := 0) vars ORDER BY calldate) t, table2 sct WHERE t.cume <= sct.bonus_seconds AND t.customer_id=sct.customer_id ;

但是,当我尝试将UPDATE与下面的命令一起使用时,它不起作用,因为不匹配任何内容。

    UPDATE table1 SET skipbill=1 WHERE sqlid=(SELECT t.sqlid FROM (SELECT t.*, (@cume := @cume + billsec) AS cume FROM table1 t CROSS JOIN (SELECT @cume := 0) vars ORDER BY calldate) t, table2 sct WHERE t.cume <= sct.bonus_seconds AND t.customer_id=sct.customer_id ) ;

如何使用该查询或更好的查询编写更新任务?

先感谢您


阅读 233

收藏
2021-04-15

共1个答案

小编典典

UPDATE table1
SET skipbill = 1
WHERE sqlid IN (
SELECT DISTINCT t.sqlid
FROM (
SELECT t.*, (@cume := @cume + billsec) AS cume
FROM table1 t
CROSS JOIN (SELECT @cume := 0) vars
ORDER BY calldate
) t, table2 sct
WHERE t.cume <= sct.bonus_seconds
AND t.customer_id = sct.customer_id
);

2021-04-15