MySQL:我怎样才能找出哪一行具有更大的价值?

时间:2011-01-05 08:28:35

标签: mysql

最终,我正在尝试删除重复的行,并使用较大的数字数据保留行。因此,要查找重复数据,我会使用:

SELECT * FROM tbl GROUP BY a HAVING COUNT(a)>1

现在,如何找到列field_a中包含大号的行?

3 个答案:

答案 0 :(得分:0)

也许(有点像警察):

DELETE t
FROM t
EXCEPT (max-query-on-t)

还要考虑两个记录具有相同最大值的情况。

答案 1 :(得分:0)

delete tbl from tbl, 
(
  select a, max(field_a) as max_a
  from tbl
  group by a 
  having count(a)>1
) as max_for_a
where tbl.a=max_for_a.a and tbl.field_a!=max_for_a.max_a;

如果每个a的field_a有两个或更多的值,它将无法删除所有

要解决此问题,您需要运行另一个查询,例如

select a, count(*) from tbl group by a;

并为每一个

delete from tbl where a=? limit (total_count-1);

答案 2 :(得分:0)

要在一个查询中执行此操作,您需要一个唯一键,并且必须将中间结果存储在临时表中:

delete from tbl where tbl.id in (select result.id from (select tbl.id from tbl join (select max(a) as a from tbl) as maxa where tbl.a<>maxa.a) as result)

我建议在两到三个单独的查询中拆分它。