当昨天的数据与今天的数据匹配时,MySQL会从表中删除特定的行

时间:2013-02-13 13:27:24

标签: mysql database join inner-join

我有一些数据存储在名为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)中与my_id和金额相同的所有行(2013-02-13)。

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

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

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

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

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

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

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

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

2 个答案:

答案 0 :(得分: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());

答案 1 :(得分: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
祝你好运。