0

如果我使用:

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)

这将返回条件 ID 为 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 的条件。他们不应该。我该如何解决?

4

1 回答 1

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)

尽管我希望这会慢得多。

您可以将第一个版本转换为 useNOT EXISTS而不是NOT IN; 不同版本的 PG 对它们进行了不同的优化,一个可能比另一个更快。

于 2012-12-13T18:42:39.917 回答