加入它们的字段不是唯一的我试图更新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? –