从另一个 table 列值更新列

Update column from another table column value

我正在尝试从 comment_users table user_id 匹配 comment_id 的评论 table 列值更新 user_id 列评论 table id 列。

comment_users table

id: 5 comment_id: 1, user_id: 20

评论table
之前

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

我不知道哪里出了问题。

您缺少 table 评论名称?

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

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

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