加入它們的字段不是唯一的我試圖更新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
我看了這裏,發現很多相關的更新帖子,但似乎沒有解決這個問題。我確信這很簡單,我錯過了。
你可能想看看這個問題:http://stackoverflow.com/questions/224732/sql-update-from-one-table-to-another-based-on-a- id-match – drdwilcox
你的第二個查詢似乎也是正確的。 –
好奇:什麼'SELECT COUNT(*)FROM table2 WHERE field ='topics'' return? –