Postgres不是不工作

时间:2012-12-11 17:38:31

标签: sql postgresql notin

如果我使用:

SELECT *
  FROM "moves"
 INNER
  JOIN "move_conditions"
    ON "move_conditions"."move_id" = "moves"."id"
 INNER
  JOIN "conditions"
    ON "conditions"."id" = "move_conditions"."condition_id"
 WHERE "conditions"."id" IN (29, 3)

这将返回条件具有29或3的正确表格。

但是,如果我尝试:

SELECT *
  FROM "moves"
 INNER
  JOIN "move_conditions"
    ON "move_conditions"."move_id" = "moves"."id"
 INNER
  JOIN "conditions"
    ON "conditions"."id" = "move_conditions"."condition_id"
 WHERE "conditions"."id" NOT IN (29, 3)

结果不正确。结果为id为29或3的条件。他们不应该。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

你的意思是如果任何的条件是29或3,你想取消移动资格吗?我会为此尝试一个子查询。

SELECT *
  FROM "moves"
WHERE moves.id
NOT IN 
    (SELECT /* Don't know if PG infers or would be faster
                 with the DISTINCT that is implied by NOT IN */
      moves.id FROM 
      move_conditions 
      INNER JOIN
      conditions
    ON move_conditions.condition_id=conditions.id
    WHERE conditions.id IN (29,3)
    )

或者你可以试试

SELECT *
  FROM moves
EXCEPT
SELECT *
  FROM "moves"
INNER
JOIN "move_conditions"
   ON "move_conditions"."move_id" = "moves"."id"
INNER
JOIN "conditions"
ON "conditions"."id" = "move_conditions"."condition_id"
WHERE "conditions"."id" IN (29, 3)

虽然我希望它会慢得多。

您可以将第一个版本转换为使用NOT EXISTS而不是NOT IN; PG的版本以不同的方式优化,一个可能比另一个更快。