建表SQL语句如下:create table main_info_04
(
userId   int unsigned ,
 shortUrl   varchar(256),
firstTime  int unsigned ,
updateTime  int unsigned ,
 clickTimes  int unsigned
PRIMARY KEY(userId,shortUrl)
);insert into main_info_04 values(406951382,'xxxxxx',123566,12312,2),(406951382,'dddddd',41241231,454354.3)
我想实现这样子的功能:
如果表中属于userId的记录条数大于1000,则删除该userId下的记录,使得只剩下1000条。
如果发现某条记录的firstTime值距离今天已经超过1个月了,则将这些记录删除。
在上述两个条件中,优先删除 clickTimes较小的记录。请问这个功能可以用SQL语句实现吗?
如果能,求SQL语句,谢谢!

解决方案 »

  1.   

    建议你只保留一个执行效率高的删除一个月前数据的操作,第一个操作效率高不了写个crontab  里面有一个sql执行date1=`date +%Y-%m-%d -d"30 days ago"`
    mysql -e "delete from tb where firstTime<'$date1'"
      

  2.   


    如果就是想实现这个:
    如果表中属于userId的记录条数大于1000,则删除该userId下的记录,使得只剩下1000条。
    该如何用SQL语句实现呢?
    谢谢!@