是否可以执行SELECT ... FROM ... WHERE ... OR ... IN(在子查询中检查2个条件)?

时间:2019-04-06 16:53:17

标签: java sqlite

我想检查表的2列中的任何一列是否与子查询的结果匹配。当前,我正在执行SELECT ... FROM ... WHERE(子查询中的var1或子查询中的var2),并且可以正常工作。但是那两个子查询是相同的,所以我认为如果我可以检查子查询中是否有var1或var2可以提高性能。不用两次执行子查询就可以做到吗?

我已经尝试过类似SELECT ... FROM ...子查询中的var1或var2的操作,但这当然不起作用,因为WHERE会将其视为2个不同的条件,例如(var1)或(var2 IN SUBQUERY )。 我现在想提高性能的当前查询如下:

SELECT table1.id FROM table1 WHERE (table1.first IN (SELECT table2.id FROM table2 WHERE (table2.xCord BETWEEN ? AND ?) AND (table2.yCord BETWEEN ? AND ?)) OR table1.second IN (SELECT table2.id FROM table2 WHERE (table2.xCord BETWEEN ? AND ?) AND (table2.yCord BETWEEN ? AND ?)))

所以子查询是这样:

SELECT table2.id FROM table2 WHERE (table2.xCord BETWEEN ? AND ?) AND (table2.yCord BETWEEN ? AND ?)

2 个答案:

答案 0 :(得分:0)

我认为这是不可能的,但是也许您最好使用通用的表表达式并且仍然使用左连接。

https://www.sqlite.org/lang_with.html

with subquery as (select col ....)
select table.* from table
    left join subquery s1 on table.var1 = s1.col
    left join subquery s2 on table.var2 = s2.col
where not (s1.col is null and s2.col is null)

这仅执行一次查询,左联接包含表中的所有行。如果子查询中没有行要加入var1,则s1.col为null。与s2类似。因此,如果两者都为null,则不会在最终结果中包括该行。根据您的数据,您可能需要select distinct

答案 1 :(得分:0)

您可以将子查询嵌套在WITH子句中,并使用如下所示的CTE:

with cte as (
  SELECT id FROM table2 
  WHERE (xCord BETWEEN ? AND ?) AND (yCord BETWEEN ? AND ?)
)
SELECT id FROM table1 
WHERE (first IN cte) OR (second IN cte)