[英]MySQL delete rows based on value and after a timestamp for each customer
I am trying to delete rows after a timestamp for each customer who have value 1 in MySQL. 我试图为每个在MySQL中具有值1的客户在时间戳后删除行。 Example table: 表格示例:
id | timestamp | cust_ID | value 899900 | 2016-04-11 12:00:00 | 500219 | 0 899901 | 2016-04-12 16:00:00 | 500219 | 0 899902 | 2016-04-14 11:00:00 | 500219 | 1 899903 | 2016-04-15 12:00:00 | 500219 | 1 899904 | 2016-04-23 09:00:00 | 500219 | 0 899905 | 2016-05-02 19:00:00 | 500219 | 0 909901 | 2016-04-12 16:00:00 | 500230 | 0 909902 | 2016-04-14 11:00:00 | 500230 | 1 909903 | 2016-04-15 12:00:00 | 500230 | 1 909904 | 2016-04-23 09:00:00 | 500230 | 0 909905 | 2016-05-02 19:00:00 | 500230 | 0 939905 | 2016-05-02 19:00:00 | 500240 | 0
Trying to achieve: 试图实现:
id | timestamp | cust_ID | value 899900 | 2016-04-11 12:00:00 | 500219 | 0 899901 | 2016-04-12 16:00:00 | 500219 | 0 899902 | 2016-04-14 11:00:00 | 500219 | 1 899903 | 2016-04-15 12:00:00 | 500219 | 1 909901 | 2016-04-12 16:00:00 | 500230 | 0 909902 | 2016-04-14 11:00:00 | 500230 | 1 909903 | 2016-04-15 12:00:00 | 500230 | 1 939905 | 2016-05-02 19:00:00 | 500240 | 0
So far I have the following which throws error 1242 'subquery returns more than one row': 到目前为止,我有以下引发错误1242“子查询返回多个行”的错误:
CREATE VIEW
max_id
AS SELECT id
, cust_ID
, MAX( timestamp
) FROM table
WHERE value
= 1 GROUP BY cust_ID
; DELETE FROM max_id
WHERE id
> (SELECT id
FROM max_id
GROUP BY cust_ID
);
Any help would be greatly appreciated! 任何帮助将不胜感激!
I'm not 100% what the exactly logic you want is. 我不是100%想要的确切逻辑。 But, you should be able to use a join
. 但是,您应该能够使用join
。 The following deletes all rows for a customer whose timestamp is greater than the maximum timestamp with a "1" for that customer: 以下内容删除该客户的时间戳大于最大时间戳且该客户带有“ 1”的所有行:
delete t
from table t join
(select t.cust_Id, max(timestamp) as maxts
from table t
group by t.cust_id
) tt
on t.cust_id = tt.cust_id and tt.timestamp > t.timestamp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.