Mysql 如何通过中介从表中获取数据

Mysql 如何通过中介从表中获取数据,mysql,join,Mysql,Join,我有三张桌子: // users +----+------+------------+ | id | name | reputation | +----+------+------------+ // posts +----+-------+---------+ | id | title | user_id | +----+-------+---------+ // votes +----+---------+---------+ | id | user_id | post_id | +--

我有三张桌子:

// users
+----+------+------------+
| id | name | reputation |
+----+------+------------+

// posts
+----+-------+---------+
| id | title | user_id |
+----+-------+---------+

// votes
+----+---------+---------+
| id | user_id | post_id |
+----+---------+---------+
注意:
投票中的用户id
属于投票人。但是
posts
表中的
user\u id
属于撰写该帖子的人

所以我想给帖子的所有者+5个代表,当他的评论获得投票时

示例:当userA向帖子投上一票(由userB编写)时,我想运行以下命令:

update users set reputatuin=reputation+5 where id = {how get the id of userB}

现在我想知道,我应该如何获得userB(编写它的帖子所有者)id?

UPDATE
语句中,您必须使用
posts
加入
投票表

如果要通过定位新投票的
投票.id
进行更新,请在
WHERE
子句中使用该选项

UPDATE 
  users
  INNER JOIN posts ON users.id = posts.user_id
  INNER JOIN votes ON votes.post_id = posts.id
SET
  users.reputation = users.reputation + 5
WHERE votes.id = {vote id to update}
UPDATE users
SET reputation = reputation + 5
WHERE 
  id = (SELECT user_id FROM posts WHERE post_id = {post id of new vote})
如果您的代码已经知道投票帖子的
posts.id
,则无需加入
投票
表,您可以使用
用户
帖子

UPDATE 
  users
  INNER JOIN posts ON users.id = posts.user_id
SET
  users.reputation = users.reputation + 5
WHERE posts.id = {post id of new vote}
使用
WHERE
子句中的子查询也可以轻松完成此查询

UPDATE 
  users
  INNER JOIN posts ON users.id = posts.user_id
  INNER JOIN votes ON votes.post_id = posts.id
SET
  users.reputation = users.reputation + 5
WHERE votes.id = {vote id to update}
UPDATE users
SET reputation = reputation + 5
WHERE 
  id = (SELECT user_id FROM posts WHERE post_id = {post id of new vote})

投票
表是否也有一个
post\u id
列来标识投票的帖子?@MichaelBerkowski是的,我编辑过!关键是确定帖子的所有者。如果你有空闲时间,如果可能的话,请看看我的新问题。你总是给我想要的东西。。。