我试图在MySQL的值为1的每个客户的时间戳之后删除行。示例表:
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
努力实现:
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
到目前为止,我有以下内容抛出错误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
);
非常感谢任何帮助!
答案 0 :(得分:0)
我不是100%你想要的逻辑是什么。但是,您应该可以使用join
。以下内容删除时间戳大于最大时间戳的客户的所有行,其中" 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