【问题标题】:Postgres NOT IN not workingPostgres NOT IN 不工作
【发布时间】:2012-12-11 17:38:30
【问题描述】:

如果我使用:

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 的条件。他们不应该。我该如何解决这个问题?

【问题讨论】:

  • 请发布样本数据(例如在sqlfiddle.com)。 NOT IN肯定在 PostgreSQL 中正常工作
  • 这似乎没问题,你能发布你的整个查询吗?
  • 可能是from tbl1, tbl2 where风格查询?
  • 可能提供的示例没有应有的准确,但请确保检查条件中没有 NULL 值:NOT IN (NULL, 29, 3)
  • 尝试改写为 conditions.id 29 和 conditions.id 3.. 看看是否正常。或者也尝试强制转换 conditions.id::int.

标签: sql postgresql notin


【解决方案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 对它们进行了不同的优化,一个可能比另一个更快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2013-07-26
    • 2021-09-12
    • 2021-02-03
    相关资源
    最近更新 更多