从另一个表列值更新列

时间:2017-06-05 09:15:24

标签: mysql mysql-5.7

我尝试更新comment_users表user_id列值的评论表上的user_id列,其中comment_id与评论表id列匹配。

comment_users表

id: 5 comment_id: 1, user_id: 20

评论表

id:1 user_id: NULL

id: 1 user_id: 20

我在下面执行了sql,但它没有工作。

UPDATE comments
  SET user_id = comment_users.user_id
  INNER JOIN comment_users ON comment_users.comment_id = comments.id
  WHERE comment_users.comment_id = comments.id


Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN comment_users ON comment_users.comment_id = comment' at line 3:       UPDATE comments
      SET user_id = comment_users.user_id
      INNER JOIN comment_users ON comment_users.comment_id = comments.id
      WHERE comment_users.comment_id = comments.id

我不知道出了什么问题。

2 个答案:

答案 0 :(得分:3)

您的update join语法错误,请尝试以下操作:

UPDATE comments
INNER JOIN comment_users ON comment_users.comment_id = comments.id
SET comments.user_id = comment_users.user_id

答案 1 :(得分:0)

你错过了评论的表名吗?

UPDATE comments
SET user_id = comment_users.user_id
FROM [table_name] comments
INNER JOIN comment_users ON comment_users.comment_id = comments.id
WHERE comment_users.comment_id = comments.id