代码之家  ›  专栏  ›  技术社区  ›  JorgeeFG

更新表,根据关系设置ID。未找到列

  •  0
  • JorgeeFG  · 技术社区  · 3 年前

    我有以下更新声明,但它说 [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
    );
    

    基本上有 brands workspaces .新列 workspace_id 作为外键添加,并且可以通过关系找到工作区id brand -> has user_id -> user has team -> team has workspace_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
    )
    
    1 回复  |  直到 3 年前
        1
  •  0
  •   user18098820 user18098820    3 年前

    不能在联接条件中使用来自品牌的列,但可以在子查询的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<>不停摆弄 here