如何避免为IN子句重复此子查询?

Tom*_*han 2 sql dry subquery in-clause

我有一个SQL脚本(目前针对SQLite运行,但它可能适用于任何数据库引擎),它使用相同的子查询两次,因为它可能会获取大量记录(该表有几百万行)I'我只想打电话一次.

缩短的伪查询版本如下所示:

SELECT * FROM
    ([the subquery, returns a column of ids]) AS sq
[a couple of joins, that fetches things from other tables based on the ids]
WHERE thisorthat NOT IN ([the subquery again])
Run Code Online (Sandbox Code Playgroud)

我尝试sq以各种方式使用name()(有/无括号,有/无命名sq等列),但无济于事.

难道我真的重复这个子查询?

澄清: 我在python和sqlite中这样做是一个可以完成的小演示,但我希望我的解决方案尽可能少地进行修改.在实际情况中,数据库将有几百万行,但在我的示例中,只有10行具有虚拟数据.因此,在例如MySQL上进行了优化的代码绝对足够好 - 它不必专门针对SQLite进行优化.但正如我所说,需要的修改越少越好.

Jan*_*net 9

WITH标准SQL中有一个子句,但是,我不知道SQLlite是否支持它 - 虽然当然值得一试:

WITH mySubQuery AS
(
  [the subquery code]
)

SELECT * FROM
    mySubQuery AS sq
    [a couple of joins, that fetches things from other tables based on the ids]
WHERE thisorthat NOT IN (mySubQuery)
Run Code Online (Sandbox Code Playgroud)

也就是说,对于任何超过几千行的数据集,你在这里所做的事情可能会非常慢,所以如果可能的话,我会尝试重新设计它 - NOT IN一般应该避免,特别是如果你还有一些连接.


one*_*hen 5

您是否需要子查询?您可能使用OUTER JOIN类似如下的代码进行重写:

SELECT * 
  FROM [the subquery's FROM clause] AS sq
       RIGHT OUTER JOIN [a couple of tables based on the ids]
          ON thisorthat = sq.[a column of ids]
 WHERE sq.[a column of ids] IS NULL;
Run Code Online (Sandbox Code Playgroud)