首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用java从mysql db中删除重复的行

如何使用java从mysql db中删除重复的行
EN

Stack Overflow用户
提问于 2018-09-21 01:13:22
回答 3查看 814关注 0票数 1

我想使用jdbc删除表中的重复行。

我只是试着在下面的代码中删除表中的所有记录

代码语言:javascript
复制
   String query="Delete from tests where product_id=20 and product_name='KINDLE001'";

有没有办法删除重复的记录,并在表中保留最后一个重复的值?

例如,表中有一列名为S.NO 1, 2,3和1,2的行是重复的,那么我只想删除记录1,并保留2,3个唯一的记录。

有什么线索吗?

EN

回答 3

Stack Overflow用户

发布于 2020-10-08 20:28:02

取决于你的数据库有多大。如果你想得到一个非常快的结果,最好使用批处理命令。例如,您有一个简单的表,其中包含以下字段: id、姓名、姓氏和年龄。再次假设您希望删除所有重复的姓名字段,只保留年龄最大的person (我只是想给出一个示例,以便它具有所有条件)。首先,创建表的模型类(我总是更喜欢定义模型类)。然后,创建所需的getter、setter和最后的构造函数。

代码语言:javascript
复制
  public class modelRecord {
        int id;
        int age;
        String name;
        String surname;
      public modelRecord() {
            super();
        }
      public modelRecord(int age, String name) {
        super();
        this.age= age;
        this.name= name;
    }
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age= age;
    }
// the same for other fields
    }

创建另一个类作为您的DAO代码。接下来,您可以搜索表以创建记录重复的列表。假设您调用了数据模型modelRecord.class,那么这意味着您必须定义一个函数,该函数返回此类类型的列表:

代码语言:javascript
复制
public List<modelRecord>  ListDuplicatedReviewId() {
   
   Connection con=null;
    ResultSet rs=null;
    List<modelRecord> list=new ArrayList<modelRecord>();
    PreparedStatement ps=null;


 // your code for accessing to db   DeleteQuery="SELECT max(age), name, COUNT(*) countNum FROM table_name GROUP BY `name` HAVING countNum > 1"; ps=con.prepareStatement(DeleteQuery); rs = ps.executeQuery();
                while (rs.next()) {
                    int maxAge=rs.getInt(1);
                    String name=rs.getString("name");
                    modelRecordrec=new modelRecord(age, name);
                    list.add(rec);
                } // close all your db connection resources
return list;
    }

然后,您可以使用此列表在mysql中应用批量删除:

代码语言:javascript
复制
public void DeleteBatch(List<modelRecord> list) throws SQLException {
    final String deleteQueryBatch="Delete from table_name where name=? AND age <?";

    try(Connection con=// get your connection to db with batch command support)){
        try(PreparedStatement ps=con.prepareStatement(deleteQueryBatch)){
        
            con.setAutoCommit(false);
        
            for (modelRecord rec : list) {
                ps.setString(1, rec.getName() );
                
                ps.setInt(2, rec.getAge());
                
                ps.addBatch();
            
            }
            
            
            int[] result =ps.executeBatch();
            int sum1 = IntStream.of(result).sum();
            System.out.println("PreparedStatement Batch executed, DELETE done= " + sum1);
            con.commit();
        
        } catch (SQLException e) {
            con.rollback();
            System.out.println(e);
        }
    }
    
}

最后,您需要一个类来调用这两个方法。我希望我已经解释清楚了。

现在是第二种方法,以防你的表没有很多记录。执行普通的内连接删除,并且不需要批处理命令。为了做到这一点,您只需要一个表的副本。我在这里只写了一个查询:

代码语言:javascript
复制
DeleteQuery=" delete table1 from table1 inner join table2 on table1.id=table2.id where table1.name=table2.name and table1.age<table2.age"
票数 1
EN

Stack Overflow用户

发布于 2018-09-21 01:52:14

您可以使用here中提到的以下方法

代码语言:javascript
复制
Select all unique rows
Copy them to a new temp table
Truncate original table
Copy temp table data to original table
票数 0
EN

Stack Overflow用户

发布于 2019-07-13 16:07:04

代码语言:javascript
复制
private void delete_duplicatesActionPerformed(java.awt.event.ActionEvent evt) {                                                  

    Connection connection = getConnection();
    try {
            String querydi = "DELETE t1 FROM winner_loser AS t1 ,winner_loser AS t2 where t1.date='"+getdate1.getText()+"' AND t2.date='"+getdate1.getText()+"'  AND t1.k=t2.k AND t1.sn>t2.sn  ";
            pstmt = (PreparedStatement) connection.prepareStatement(querydi);

            pstmt.executeUpdate();

            JOptionPane.showMessageDialog(null, "Delete Duplicates Successfully ! Reload again pls !");

            pstmt.close();
            connection.close();
        } catch (SQLException ex) {

        }     
}    

上面的代码运行良好,可以删除重复的值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52430144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档