我正在尝试使用table2中的数据(来自'data')更新一个table1('keyword')中的列,他们在'itemid'上加入。然而,'itemid'在table2中并不是唯一的,我仍然坚持如何从记录中获取与正确的'field'匹配的数据来更新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帖子,但似乎都没有解决这个问题。我确信这很简单,我很想念。
答案 0 :(得分:0)
UPDATE table1 AS t1
SET t1.keywords =
( SELECT t2.data
FROM table2 AS t2
WHERE t1.itemid = t2.itemid
AND t2.field='topics'
)
答案 1 :(得分:-1)
UPDATE table1 t1, table2 t2
SET t1.keywords = t2.data
WHERE t1.itemid = t2.itemid
AND t2.field = 'topics'