PostgreSQL删除和加入时的歧义查询?

时间:2019-07-11 12:14:57

标签: sql postgresql join sql-delete

我有以下查询

DELETE FROM bookings 
    where "bookings"."memberId" IN (
      select "memberId" from "bookings"
      join "memberRoles" on "memberRoles"."memberId" = "bookings"."memberId"
      where "bookings"."memberId" = 1234
      and "bookings"."state" = 'MATCHED'
      and "memberRoles"."roleId" in (354,326,184)
    );

我的预期输出是删除我要求删除的所有内容,但是,它在SELECT内的IN中返回了一个错误,该错误是 ERROR: column reference "memberId" is ambiguous

我尝试做select "bookings"."memberId",但随后会说

ERROR: syntax error at or near "join"

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

限定所有列名称。我建议使用表别名:

DELETE FROM bookings b
    where b."memberId" IN (
      select b2."memberId"
      from "bookings" b2 join
           "memberRoles" mr
           on mr."memberId" = b2."memberId"
      where b2."memberId" = 1234 and
            b2."state" = 'MATCHED' and
            mr."roleId" in (354, 326, 184)
    );

不过,我认为您不需要in。您可能要测试一下:

DELETE bookings b
    FROM "memberRoles" mr
    WHERE mr."memberId" = b."memberId" AND
          b."memberId" = 1234 AND
          b."state" = 'MATCHED' AND
          mr."roleId" in (354, 326, 184);