2016-07-31 48 views
0

我想删除每个客户在MySQL中具有值1的时间戳后的行。示例表:MySQL基于每个客户的价值和时间戳后删除行

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 idcust_ID,MAX(timestamp)FROM table WHERE value = 1 GROUP BY cust_ID; (选择idmax_id GROUP BY cust_ID);

任何帮助将不胜感激!

回答

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 
+0

谢谢您的回答。然而,这只保留每行cust_id一行。任何帮助,将不胜感激。 –

+0

它现在可以工作,我切换了tt.timestamp> t.timestamp。谢谢! –