MySQL根据列的最大值删除行

时间:2014-06-22 15:23:16

标签: mysql database sql-delete

我有一个表('conditions'),其中包含一个标题为“Date”的列我想删除所有不等于当前日期的行(由date(MAX(DATE))的最大值确定。部分表结果:

| Date     | Time  | Observed                     | Temp | HeatIndex | WindChill | RelHumidity | Wind
| 14-06-21 | 19:30 | Scattered Clouds             | 85.9 | 91        | NA        | 61%         |    2 |
| 14-06-21 | 20:30 | Clear                        | 83.2 | 88        | NA        | 67%         |    3 |
| 14-06-21 | 21:30 | Clear                        | 80.7 | 85        | NA        | 74%         |    5 |
| 14-06-21 | 22:30 | Clear                        | 79.5 | 83        | NA        | 76%         |    4 |
| 14-06-21 | 23:30 | Clear                        | 78.4 | 81        | NA        | 79%         |    4 |
| 14-06-22 | 00:30 | Clear                        | 77.6 | NA        | NA        | 82%         |    3 |
| 14-06-22 | 01:30 | Clear                        | 77.1 | NA        | NA        | 83%         |    3 |
| 14-06-22 | 02:30 | Scattered Clouds             | 77.3 | NA        | NA        | 84%         |    2 |
| 14-06-22 | 03:30 | Clear                        | 77.1 | NA        | NA        | 83%         |    2 |
| 14-06-22 | 04:30 | Clear                        | 76.6 | NA        | NA        | 86%         |    4 |

所以在命令之后,我想看到以下内容:

| 14-06-22 | 00:30 | Clear                        | 77.6 | NA        | NA        | 82%         |    3 |
| 14-06-22 | 01:30 | Clear                        | 77.1 | NA        | NA        | 83%         |    3 |
| 14-06-22 | 02:30 | Scattered Clouds             | 77.3 | NA        | NA        | 84%         |    2 |
| 14-06-22 | 03:30 | Clear                        | 77.1 | NA        | NA        | 83%         |    2 |
| 14-06-22 | 04:30 | Clear                        | 76.6 | NA        | NA        | 86%         |    4 |

我试过了:

DELETE FROM conditions WHERE Date <> MAX(Date);

但收到了:

ERROR 1111 (HY000): Invalid use of group function

最后一行始终是当前日期。我考虑过添加ID列并按DESC排序,但我希望最后一行是最新的一行。每次我将数据(python)插入数据库时​​,都会执行包含Delete的脚本。

2 个答案:

答案 0 :(得分:2)

标准的SQL是:

DELETE
    FROM conditions
    WHERE Date < (select MAX(Date) from conditions)

然而,当你在where子句中使用同一个表时,MySQL并不喜欢它。所以改为使用连接:

delete c
    from conditions c join
         (select max(date) as maxdate from conditions) x
         on c.date < x.maxdate;

答案 1 :(得分:0)

非常确定您不能使用MAX的原因与您无法在删除时查询当前表的原因相同。

您可以使用CURDATE()

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate

DELETE FROM conditions WHERE Date <> CURDATE();