zoukankan      html  css  js  c++  java
  • MySQL 数据库查询数据,过滤重复数据保留一条数据---(MySQL中的row_number变相实现方法)

    转自: http://www.maomao365.com/?p=10564  摘要:

    下文讲述MySQL数据库查询重复数据时,只保留一条数据的方法 
    实现思路:
    在MySQL数据库中没有row_number函数,所以我们需变向实现此功能。
     

    --1.基础数据表查看
    mysql> select * from `maomao365.com`;
    +-------+------------+
    | keyId | infoB |
    +-------+------------+
    | 1 | mysql test |
    | 129 | sql |
    | 12913 | sql |
    | 12913 | sql |
    | 12913 | sql |
    +-------+------------+
    5 rows in set (0.00 sec)
    
    ---2 群组编号
    mysql> select if(@keyId=a.keyId and @infoB=a.infoB,@r:=@r+1,@r:=1) as rowNumber,a.*,@keyId:=a.keyId,@infoB:=a.infoB
    -> from (select @keyId:=null,@infoB:=null,@r:=0) r, (select keyId,infoB from `maomao365.com` order by keyId) a;
    +-----------+-------+------------+-----------------+-----------------+
    | rowNumber | keyId | infoB | @keyId:=a.keyId | @infoB:=a.infoB |
    +-----------+-------+------------+-----------------+-----------------+
    | 1 | 1 | mysql test | 1 | mysql test |
    | 1 | 129 | sql | 129 | sql |
    | 1 | 12913 | sql | 12913 | sql |
    | 2 | 12913 | sql | 12913 | sql |
    | 3 | 12913 | sql | 12913 | sql |
    +-----------+-------+------------+-----------------+-----------------+
    5 rows in set (0.00 sec)
    
    ---3 重复数据只显示一条
    mysql> select * from (select if(@keyId=a.keyId and @infoB=a.infoB,@r:=@r+1,@r:=1) as rowNumber,a.*,@keyId:=a.keyId,@infoB:=a.infoB
    -> from (select @keyId:=null,@infoB:=null,@r:=0) r, (select keyId,infoB from `maomao365.com` order by keyId) a
    -> ) as t where t.rowNumber =1;
    +-----------+-------+------------+-----------------+-----------------+
    | rowNumber | keyId | infoB | @keyId:=a.keyId | @infoB:=a.infoB |
    +-----------+-------+------------+-----------------+-----------------+
    | 1 | 1 | mysql test | 1 | mysql test |
    | 1 | 129 | sql | 129 | sql |
    | 1 | 12913 | sql | 12913 | sql |
    +-----------+-------+------------+-----------------+-----------------+
    3 rows in set (0.00 sec)

    定义临时变量 @keyId,@infoB
    每次查询时 都重新对 @keyId,@infoB 赋值
    在赋值前,都采用If对其进行判断,如果当前行记录信息和临时变量中的值相同时,则作为相同数据@r变量加1,否则@r变量变为1
    采用以上模式,可以将重复的行记录进行编号

    最后对重新编号后的记录,检索出row_number等于1的信息
      Mysql row_number函数实现方法

  • 相关阅读:
    转 哪个家伙说“网站去.Net化”?
    javascript prototype
    Spring作用,MVC容器作用
    javascript 闭包
    导入Excel数据至Access 宁静以致远
    My first mobile message 宁静以致远
    MyEclipse遇到的错误
    JAVAEE错误处理
    JavaEE ActionForm的高级应用
    hibernate
  • 原文地址:https://www.cnblogs.com/lairui1232000/p/11826772.html
Copyright © 2011-2022 走看看