2011-04-22 171 views
1

我錯了,在我的MySql表中添加一些參考。我認爲一個例子會告訴你我的問題(我真的希望如此)。這是我的表的結構的一個例子:我怎麼能翻譯這個參考

tableMain 
id (int) 
trackid(varchar) 
data(text) 

tableArtist 
idArtist(int) 
ref(varchar) 
artist(varchar) 

tableEvent 
idEvent(int) 
ref(varchar) 
event(varchar) 

這些是DATAS:

tableMain 
1  abc primo 
2  def secondo 
3  ghi terzo 

tableArtist 
1  abc artist2 
2  abc artist4 
3  ghi artist5 
4  def artist1 
5  ghi artist3 

tableEvent 
1  def event1 
2  abc event5  
3  222 event3 
4  ghi event2 
5  abc event4 

我想更改tableEvent和tableArtist都與的值替換ref的值在corespondent ID弗羅姆tableMain:

tableMain 
1  abc  primo 
2  def  secondo 
3  ghi  terzo 

tableArtist 
1  1  artist2 
2  1  artist4 
3  2  artist5 
4  2  artist1 
5  3  artist3 

tableEvent 
1  2  event1 
2  1  event5  
3  2  event3 
4  3  event2 
5  1  event4 

是否有可能對MySQL或我需要一種腳本(如PHP)來完成的呢?

回答

2
UPDATE tableArtist, tableMain 
    SET tableArtist.ref = tableMain.id 
    WHERE tableArtist.ref = tableMain.trackid 

UPDATE tableEvent, tableMain 
    SET tableEvent.ref = tableMain.id 
    WHERE tableEvent.ref = tableMain.trackid 

編輯:爲了解決@ colinmarc的關注,更新您可以將數據經過:

ALTER TABLE tableArtist MODIFY ref INT; 
ALTER TABLE tableEvent MODIFY ref INT; 
+0

這個問題是'ref'仍然將是一個'varchar' ... – colinmarc 2011-04-22 20:17:03

+0

@colinmarc :如果需要,數據類型肯定可以隨後修改。 – 2011-04-22 20:18:27

1

您可以用幾個疑問做到這一點,是的。使用您的命名約定:

ALTER TABLE tableArtist ADD COLUMN idMain int; 
UPDATE tableArtist SET idMain = (
    SELECT id FROM tableMain where tableArtist.ref = tableMain.trackid 
); 

然後,一旦你知道數據是好的:

ALTER TABLE tableArtist DROP COLUMN ref; 
+0

通過在此處引入完全不同的列名稱,您可能正在考慮重構大量代碼。 – 2011-04-22 20:19:39

+0

這是一個很好的觀點。你可以隨時更改名稱 - 但我沒有意識到你可以在填充後改變列的類型,這樣也可以。 – colinmarc 2011-04-22 20:21:15