如何在更新语句的 "set" 部分引用正在更新的 table?

How do I reference the table being updated in the "set" portion of my update statement?

我正在使用 MySQL 5.5.37。我想更新 table 并且我想在我用来获取更新值的查询子句中使用我希望更新的特定行的值。因此,例如,我像这样 table 别名

update session ts set

所以我想在声明的 "set" 部分引用 "ts.id",如果可能的话。我试过了

update session ts set user_id = (select q.* from
  (select u.id FROM session t, training_session_org tso, organization o, user u
   where o.user_id = u.id and tso.organization_id = o.id
     and t.id = tso.training_session_id and t.id = ts.id) q);

但是我得到了

ERROR 1054 (42S22): Unknown column 'ts.id' in 'where clause'

如果可能的话,在查询中引用我更新的 table 的正确方法是什么?此外,我想在一个 SQL 语句中执行此操作,而不是多个语句。

问题是您正在使用双子查询并且 ts.id 超出了内部查询范围,我怀疑您试图使用它来避免错误:

You can't specify target table 'ts' for update in FROM clause

但解决方案只是从子查询中省略 session table,因为您不需要它:

update session set user_id = (select u.id
  from training_session_org tso 
  join organization o on o.id = tso.organization_id
  join user u on u.id = o.user_id
  where tso.training_session_id=session.id)

事实上,基于连接,您甚至可以进一步简化查询:

update session set user_id = (select o.user_id
  from training_session_org tso 
  join organization o on o.id = tso.organization_id
  where tso.training_session_id=session.id)