我正在尝试使用表 2 中的数据(来自“数据”)更新一个表 1(“关键字”)中的列,它们在“itemid”上加入。但是,“Itemid”在 table2 中不是唯一的,我一直在研究如何从与正确“字段”匹配的记录中获取数据以更新 table1,如下表所示:
表 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
我在这里查看并发现了很多相关的更新帖子,但似乎都没有解决这个问题。我确定这是我所缺少的简单内容。
最佳答案
UPDATE table1 t1, table2 t2
SET t1.keywords = t2.data
WHERE t1.itemid = t2.itemid
AND t2.field = 'topics'
关于mysql - UPDATE 字段从表 1 到表 2,其中连接它们的字段在表 2 中不是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8215491/