使用子查询更新表

时间:2011-07-29 21:47:54

标签: mysql sql subquery sql-update

你可以看到我想做的是:

[1]抓取与 forum_qa

中的$toggled匹配的记录的 author_id

[2]在 user_profiles 中更新声誉,其中 user_id author_id 匹配

    UPDATE  user_profiles

    (SELECT forum_qa_author_id AS author_id
    FROM    forum_qa
    WHERE   forum_qa_id = $toggled) AS f

    SET     user_profiles.reputation = user_profiles.reputation - 15
    WHERE   user_profiles.user_id = f.author_id

这在(SELECT...给我一个1064语法错误。

知道我在这里做错了吗?

感谢您的帮助!

3 个答案:

答案 0 :(得分:4)

尝试:

UPDATE  user_profiles
SET     user_profiles.reputation = user_profiles.reputation - 15
WHERE   user_profiles.user_id = (SELECT forum_qa_author_id AS author_id
FROM    forum_qa
WHERE   forum_qa_id = $toggled)

答案 1 :(得分:0)

子查询必须在“SET”之后。在这种情况下,它可能不一定需要子查询......

试试......

UPDATE user_profiles
   SET user_profiles.reputation = user_profiles.reputation - 15
  FROM user_profiles
  JOIN forum_qa f ON user_profiles.user_id = f.author_id
   AND forum_qa_id = $toggled

答案 2 :(得分:0)

UDPATE up set reputation = reputation - 15 
FROM user_profiles up inner join forum_qa fq on (up.user_id = fq.forum_qa_id) 
WHERE forum_qa_id = $toggled

我刚才意识到你正在使用MySQL。这是针对MS SQL的,我不确定你是否可以在MySQL中使用它,但希望它有点帮助......