1

我有一些数据存储在一个名为 MyTable 的 MySQL 表中,如下所示:

+----------+-----------+---------------------+
|    my_id |    amount | updated             |
+----------+-----------+---------------------+
|   105415 |        81 | 2013-02-13 00:00:00 |
|   105414 |        33 | 2013-02-13 00:00:00 |
|   220801 |       240 | 2013-02-13 00:00:00 |
|   105411 |       118 | 2013-02-13 00:00:00 |
|   105411 |       118 | 2013-02-12 00:00:00 |
|   220801 |       240 | 2013-02-12 00:00:00 |
|   105414 |        33 | 2013-02-11 00:00:00 |
|   105415 |        81 | 2013-02-11 00:00:00 |
+----------+-----------+---------------------+

我想做的是删除昨天(2013-02-12)与今天(2013-02-13)具有相同 my_id 和数量的所有行。

我知道如何选择今天的所有数据:

SELECT * FROM 'MyTable' WHERE 'updated' = CURDATE()

我知道如何选择昨天的所有数据:

SELECT * FROM 'MyTable' WHERE 'updated' = CURDATE()-1

我知道 DELETE 命令 ( DELETE FROM 'MyTable' WHERE...) 的语法。

如何删除昨天和今天 my_id 和 amount 匹配的行?

在给出的示例中,我想删除这些行:

|   105411 |       118 | 2013-02-12 00:00:00 |
|   220801 |       240 | 2013-02-12 00:00:00 |

我想保留这些行:

+----------+-----------+---------------------+
|    my_id |    amount | updated             |
+----------+-----------+---------------------+
|   105415 |        81 | 2013-02-13 00:00:00 |
|   105414 |        33 | 2013-02-13 00:00:00 |
|   220801 |       240 | 2013-02-13 00:00:00 |
|   105411 |       118 | 2013-02-13 00:00:00 |


|   105414 |        33 | 2013-02-11 00:00:00 |
|   105415 |        81 | 2013-02-11 00:00:00 |
+----------+-----------+---------------------+
4

2 回答 2

2

对@sgeddes 的回答稍作修改,我认为这对您的回答更准确:

无论如何,请把@sgeddes 的答案作为正确答案,因为他的回答引导了这一点:

DELETE t1 FROM MyTable AS t1, MyTable as t2
WHERE t1.updated = CURDATE()-1
  AND t2.updated =  CURDATE()
  AND t2.my_id = t1.my_id
  And t2.amount = t1.amount;

如果你有一个主键,你也可以使用它(这是我更喜欢的 SQL)

DELETE FROM MyTable 
WHERE  updated = CURDATE()-1 
  AND (my_id,amount) in (select my_id,amount 
                         from MyTable
                         where updated = CURDATE());
于 2013-02-13T14:36:43.217 回答
1

像这样的东西应该工作:

DELETE M
FROM MyTable M
    INNER JOIN MyTable M2 ON
        M.My_Id = M2.My_Id AND  
        M.amount = M2.amount AND  
        M2.Updated = DATE_ADD(M.Updated, INTERVAL 1 DAY)

这是更新的小提琴上面的示例数据:http ://sqlfiddle.com/#!2/5e288/1

删除后的结果:

MY_ID   AMOUNT  UPDATED
105415  81      February, 13 2013 00:00:00+0000
105414  33      February, 13 2013 00:00:00+0000
220801  240     February, 13 2013 00:00:00+0000
105411  118     February, 13 2013 00:00:00+0000
105414  33      February, 11 2013 00:00:00+0000
105415  81      February, 11 2013 00:00:00+0000

祝你好运。

于 2013-02-13T13:36:54.420 回答