mysql过滤表中重复数据_mysql过滤表中重复数据,查询相同数据的特定一条

待操作的表如下:

select * from test_max_data;

+----+----------+-------------------+

| id | area | best_history_data |

+----+----------+-------------------+

|1 | beijing| 33|

|2 | beijing| 22|

|3 | shanghai | 1 |

|4 | shanghai | 2 |

|5 | chengdu| 1 |

|6 | chengdu| 2 |

|7 | henan| 13|

|8 | henan| 12|

+----+----------+-------------------+

期待:获取各个area中best_history_data最大的一条

1.最简单的一种方式,如果只需要从表中获取area和对应的最大best_history_data,可用以下方式:

select area,max(best_history_data) best_history_data from test_max_data group by area;

+----------+-------------------+

| area | best_history_data |

+----------+-------------------+

| beijing| 33|

| chengdu| 2 |

| henan| 13|

| shanghai | 2 |

+----------+-------------------+

该方式只能获取到area和对应的最大best_history_data字段值。

2.使用联表查询的方式

select a.* from test_max_data a join (select area,max(best_history_data) best_history_data from test_max_data group by area) b where a.area=b.area and a.best_history_data=b.best_history_data;

+----+----------+-------------------+

| id | area | best_history_data |

+----+----------+-------------------+

|1 | beijing| 33|

|4 | shanghai | 2 |

|6 | chengdu| 2 |

|7 | henan| 13|

+----+----------+-------------------+

3.使用相关子查询的方式

select * from test_max_data a where a.best_history_data=(select max(best_history_data) as best_history_data from test_max_data where area=a.area);

+----+----------+-------------------+

| id | area | best_history_data |

+----+----------+-------------------+

|1 | beijing| 33|

|4 | shanghai | 2 |

|6 | chengdu| 2 |

|7 | henan| 13|

+----+----------+-------------------+

4.使用not exists的方式

select * from test_max_data a where not exists (select * from test_max_data b where a.area=b.area and a.best_history_data

+----+----------+-------------------+

| id | area | best_history_data |

+----+----------+-------------------+

|1 | beijing| 33|

|4 | shanghai | 2 |

|6 | chengdu| 2 |

|7 | henan| 13|

+----+----------+-------------------+

原文:https://www.cnblogs.com/mianbaoshu/p/12058588.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值