2011-11-21 86 views
1

加入它們的字段不是唯一的我試圖更新table1('關鍵字')與表2中的數據('數據')加入'itemid'。 「ITEMID」不表2中獨特的,但是,我卡在如何從匹配正確的「場」更新表1,如下表中的記錄中的數據:更新字段從表1到表2其中表2

表1:

|itemid | keywords 
------------------- 
| 1 |  
| 2 |  
| 3 |  
------------------- 

表2:

|itemid | field  | data    
--------------------------------------------------------- 
| 1 | author | Shakespeare   
| 1 | title  | Hamlet    
| 1 | topics | love, loyalty, treason  
| 2 | author | Dickens   
| 2 | title  | Christmas Carol  
| 2 | topics | greed, reconciliation 
| 3 | author | Melville   
| 3 | title  | Moby-Dick   
| 3 | topics | madness, immortality, sea 
--------------------------------------------------------- 

我想要實現的是這個在表1:

|itemid | keywords   
----------------------------------------- 
| 1 | love, loyalty, treason  
| 2 | greed, reconciliation 
| 3 | madness, immortality, sea 
----------------------------------------- 

什麼是日正確的查詢來完成這個?我試過這些查詢,它們不會引發任何錯誤,但它們不會更新任何行。

UPDATE table1 AS t1, table2 AS t2 SET t1.keywords=t2.data WHERE t1.itemid=t2.itemid AND t2.field='topics' 

UPDATE table1 AS t1 
    JOIN table2 AS t2 
    ON t1.itemid=t2.itemid 
SET t1.keywords=t2.data 
WHERE t2.field='topics' 

UPDATE table1 AS t1, (SELECT itemid, data FROM table2 WHERE field='topics') AS t2 SET t1.keywords=t2.data 

我看了這裏,發現很多相關的更新帖子,但似乎沒有解決這個問題。我確信這很簡單,我錯過了。

+0

你可能想看看這個問題:http://stackoverflow.com/questions/224732/sql-update-from-one-table-to-another-based-on-a- id-match – drdwilcox

+0

你的第二個查詢似乎也是正確的。 –

+0

好奇:什麼'SELECT COUNT(*)FROM table2 WHERE field ='topics'' return? –

回答

-1
UPDATE table1 t1, table2 t2 
SET t1.keywords = t2.data 
WHERE t1.itemid = t2.itemid 
    AND t2.field = 'topics' 
+0

我試過了,但得到了「0行受影響」。這不是與上面的查詢#1相同,但沒有「AS」來設置別名? 問題可以用我的實際語法嗎?這是我的真實姓名,而不是示例文本: 'UPDATE master_sobi2_item T1,T2 master_sobi2_fields_data SET = t1.metakey t2.data_txt WHERE t1.itemid = t2.itemid AND t2.fieldid = 18' –

+0

你的語法看起來不錯,查詢看起來是正確的。最好的猜測是檢查數據,以確保它排隊,並且't2.fieldid = 18'對應於您的數據 – Ryan

+0

您是對的btw,查詢是相同的。請注意,如果您運行例如'UPDATE table1 t1 SET t1.keywords ='blah'WHERE t1.itemid = 2',那麼單行將受到影響。如果您再次運行它,則不會因爲不對數據進行更改而影響行。這可能是你所看到的實際數據? – Ryan

0
UPDATE table1 AS t1 
SET t1.keywords = 
    (SELECT t2.data 
     FROM table2 AS t2 
     WHERE t1.itemid = t2.itemid 
     AND t2.field='topics' 
    )