How to delete duplicated rows and update the table

前端 未结 1 1842
旧巷少年郎
旧巷少年郎 2021-01-03 03:18

I have duplicated rows in tables.

I have two table which are connected by a foreign key

regions (id)
orders (region_id)

The region

相关标签:
1条回答
  • 2021-01-03 03:48

    To update the orders table, something like:

    update  orders
    join    regions r1
    on      r1.id = orders.region_id
    set     orders.region_id = 
            (
            select  min(r2.id)
            from    regions r2
            where   r2.name = r1.name
            )
    

    After that, you can delete duplicate rows with:

    delete  regions
    from    regions
    where   id not in
            (
            select  id
            from    (
                    select  min(id) as id
                    from    regions
                    group by
                        name
                    ) as SubqueryAlias
            )
    

    The double subquery is required to avoid the MySQL error ERROR 1093 (HY000) at line 36: You can't specify target table 'regions' for update in FROM clause.

    0 讨论(0)
提交回复
热议问题