如何从MySQL中的分组数据中删除行

时间:2015-04-21 07:17:45

标签: mysql sql

我有一张桌子:

enter image description here

我希望每个 live_login 最多留下两个条目,这些条目按 last_login_ts 排序。

结果,你应该得到:

enter image description here

如果可能,只使用SQL,不使用php和其他工具。

P.S。对不起我的英文:)

ANSWER

delete gr.* from my_table gr inner join (Select x.* from my_table x join my_table y on y.live_login = x.live_login and y.last_login_ts <= x.last_login_ts group by x.live_login, x.last_login_ts having count(*) > 2) gh on gh.live_login=gr.live_login and gh.dead_login=gr.dead_login;

谢谢,草莓

3 个答案:

答案 0 :(得分:3)

Select x.* 
  from my_table x 
  join my_table y 
    on y.live_login = x.live_login 
   and y.last_login_ts <= x.last_login_ts 
 group by x.live_login
     , x.last_login_ts 
having count(*) <= 2

或类似的东西

答案 1 :(得分:2)

编辑:显然这个符合ANSI / ISO SQL的答案不适用于MySQL。无论如何,可以与大多数其他dbms产品一起使用,所以我不会删除答案。

如果有两个(或更多)具有相同live_login的新行,则删除一行:

delete from tablename t1
where 2 <= (select count(*)
            from tablename t2
            where t2.live_login = t1.live_login
              and t2.last_login_ts > t1.last_login_ts)

答案 2 :(得分:1)

这很有效,但很难看,可能不是最理想的:

delete logins from logins
inner join (
  select l1.live_login, l1.last_login_ts second, q1.last_login_ts min 
    from logins l1
    left join
      (select live_login, min(last_login_ts) last_login_ts 
        from logins 
        group by live_login) q1
    on q1.last_login_ts < l1.last_login_ts 
      and l1.live_login = q1.live_login
    where not exists 
     (select 1 
       from logins 
       where live_login = q1.live_login 
         and logins.last_login_ts > q1.last_login_ts 
         and logins.last_login_ts < l1.last_login_ts) 
     and q1.last_login_ts is not null) q
on q.live_login = logins.live_login and logins.last_login_ts > q.second;

演示小提琴:http://sqlfiddle.com/#!9/d3145/1