2012-05-24 75 views
0

我有一個不同的入口每場比賽像這樣「遊戲」的表:合併MySQL的行不同的ID,但相當於數據

gameID internalName 
1  game1 
2  game 1 
3  game 2 
4  game2 
5  game3 

那麼,問題是現在我想結合遊戲標題(刪除空格)相同的情況。在其他遊戲ID爲2的行將與1合併,並刪除。

此外,我想更新其他表中使用gameID作爲外鍵的任何條目,以指向新的鍵。

我知道我可以做這樣的事情的話,得到一個列表,它的標題有重複:

SELECT gameID, count(REPLACE(internalName, ' ', '')), internalName FROM games GROUP BY REPLACE(internalName, ' ', '') HAVING count(REPLACE(internalName, ' ', '')) > 1 

然而,這並不能真正幫助我實現什麼,我需要做的。

任何幫助?

+0

你是什麼意思由r ow 2將與1合併並刪除?具體來說,「合併」是什麼意思?合併第2行與第1行以任何方式更改第1行? –

+0

這不是一個真正的合併,它會很痛苦,取決於你有多少外鍵給你的GameID。更糟糕的是,如果他們成爲複合鍵的一部分。鑑於你陷入了這場混亂,我試圖引入代孕鑰匙,並將其放置在牀上。 –

回答

2

類似的東西,可以幫助你開始

select g1.gameID as toKeep, g2.gameID toEliminate 
from games g1 
inner join games g2 on replace(g1.internalName, ' ', '') = replace(g2.internalName, ' ', '') 
where g1.gameID < g2.gameID 

但如果你有3項合併,這是不行的那麼好......

看到http://sqlfiddle.com/#!2/fb294/6

但內一個存儲過程或PHP(或其他語言),你應該能夠得到你想要的。

更好

與這一個,甚至3,或4,或5相同的結果將工作

select g1.gameID as toKeep, g2.gameID toEliminate 
from games g1 
inner join games g2 on replace(g1.internalName, ' ', '') = replace(g2.internalName, ' ', '') 
where g1.gameID < g2.gameID 
and g1.gameID not in (SELECT g4.gameID 
         from games g4 
         inner join games g3 on replace(g3.internalName, ' ', '') = replace(g4.internalName, ' ', '') 
         where g3.gameID < g4.gameID) 

http://sqlfiddle.com/#!2/8fb21/1

編輯:(未經測試)存儲過程

的一個例子
CREATE PROCEDURE CLEANGAMENAMES() 
BEGIN 
    DECLARE toKeep, toEliminate INT; 
    DECLARE cur1 CURSOR FOR 
    SELECT g1.gameID AS toKeep, g2.gameID AS toEliminate 
    FROM games g1 
    INNER JOIN games g2 ON REPLACE(g1.internalName, ' ', '') = REPLACE(g2.internalName, ' ', '') 
    WHERE g1.gameID < g2.gameID 
    AND g1.gameID NOT IN (SELECT g4.gameID 
          FROM games g4 
          INNER JOIN games g3 ON REPLACE(g3.internalName, ' ', '') = REPLACE(g4.internalName, ' ', '') 
          WHERE g3.gameID < g4.gameID) 

    OPEN cur1; 

    read_loop: LOOP 
    FETCH cur1 INTO toKeep, toEliminate; 
    UPDATE <anyTable> set gameId = toKeep where gameId = toEliminate; 
    -- as many tables as you need 
    DELETE FROM games where gameID = toEliminate; 
    UPDATE games set internalName = REPLACE(internalName, ' ', ''); 

    END LOOP; 

    CLOSE cur1; 
END; 
+0

感謝您的幫助! 僅供參考,以下是最終的代碼: http://code.google.com/p/game-deal-tracker/source/browse/trunk/sql/5-24-12/gameCleanUp.sql – David

相關問題