2011-08-29 50 views
5

我在表中有重複的行。如何刪除重複的行並更新表

我有一個由外鍵

regions (id) 
orders (region_id) 

的地區有重複的名字相連的兩個表。我想刪除這些重複的行和更新訂單表,現在重複的外鍵將被設置爲只保留區域表中的現有名稱。

例子:

regions table: 

id name 
1 | test 
2 | test 
3 | foo 

orders table: 

id region_id 
6 | 1 
7 | 2 
9 | 3 

我想

orders table: 

id region_id 
6 | 1 
7 | 1 
9 | 3 

regions table: 

id name 
1 | test 
3 | foo 

我可以重複的行與此SQL:

SELECT name, count(id) as cnt FROM regions 
GROUP BY name HAVING cnt > 1 

我如何連接這個選擇與順序表和刪除重複行和更新表?

+0

重複保存記錄的邏輯是什麼?我假設第一個(即最低的主鍵)。你有機會獲得另一項技術嗎?直接使用MySQL可能很難做到這一點。 –

+1

Lukas它不只是刪除行。我需要更新外鍵! – senzacionale

+0

對不起,你是對的... –

回答

5

要更新的訂單表,是這樣的:

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 
     ) 

之後,你可以刪除重複的行:

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

雙重子查詢需要避免MySQL錯誤ERROR 1093 (HY000) at line 36: You can't specify target table 'regions' for update in FROM clause

+0

@senzacionale:奇怪的是,它可以在我的MySQL安裝 – Andomar

+0

thx上尋求幫助。我不知道你需要這樣的子查詢。 – senzacionale