更新table,根据关系设置ID。找不到列

Update table, set ID based on relation. Column not found

我有以下更新语句,但它说 [42S22][1054] Unknown column 'b.user_id' in 'on clause'

UPDATE brands b set b.workspace_id = (
  SELECT w.id from workspaces w
    INNER JOIN users u on b.user_id = u.id
    inner join team_members tm on u.id = tm.user_id
    inner join teams t on tm.team_id = t.id AND w.id = t.workspace_id
);

基本上有brandsworkspaces。添加了一个新列 workspace_id 作为外键,可以通过关系 brand -> has user_id -> user has team -> team has workspace_id

找到工作区 ID

在编程方面,我可以首先找到所有要处理的工作区,然后获取该工作区的所有用户 ID,然后 运行 update brands b set workspace_id = :wsId where user_id in (:userIds)

-- auto-generated definition
create table brands
(
    id           bigint auto_increment
        primary key,
    user_id      int unsigned                  not null,
    name         varchar(100)                  null,
    workspace_id int                           null
)

您不能在连接条件中使用来自品牌的列,但可以在 sub-query

中的 where 条件中使用它
create table brands (
  workspace_id int,
  user_id int
  );
create table users (
  id int);
create table team_members(
  user_id int,
  team_id int
  );
create table teams (
  id int,
  workspace_id int
  );
create table workspaces(
  user_id int,
  id int
  );
UPDATE brands set workspace_id = (
  SELECT w.id from workspaces w
    INNER JOIN users u on w.user_id = u.id
    inner join team_members tm on u.id = tm.user_id
    inner join teams t on tm.team_id = t.id AND w.id = t.workspace_id
    WHERE brands.user_id = u.id
);

db<>fiddle here