我认为您的 RDBMS 在执行查询方面做得很差,其他 RDBMS(例如 SQL Server)可以看到,如果子查询与外部查询不相关,它将在内部实现结果并且不会重复执行子查询。例如
select *
, (select count(*) from tbl) -- an smart RDBMS won't execute this repeatedly
from tbl
一个好的RDBMS不会重复执行计数,因为它是一个独立的查询(与外部查询无关)
尝试所有选项,反正只有几个选项
第一,试试 EXISTS。您的 RDBMS 的 EXISTS 可能比它的 IN 快。我遇到的 IN 比 EXISTS 快,例如:Why the most natural query(I.e. using INNER JOIN (instead of LEFT JOIN)) is very slow Quassnoi 的相同观察(IN 比 EXISTS 快):http://explainextended.com/2009/06/16/in-vs-join-vs-exists/
SELECT count(*)
FROM TABLE1
WHERE
-- stringVal IN
EXISTS(
SELECT * -- please, don't bikeshed ;-)
FROM TABLE2
where
table1.stringVal = table2.stringVal -- simulated IN
and table2.idTable2 = 5);
第二,尝试INNER JOIN,如果没有重复就使用这个,或者使用DISTINCT删除重复。
SELECT count(*)
FROM TABLE1
JOIN (
SELECT DISTINCT stringVal -- remove duplicates
FROM TABLE2
where table2.idTable2 = 5 ) as x
ON X.stringVal = table1.stringVal
第三,尝试自己实现这些行。我在使用 SQL Server 时遇到了同样的问题,查询具体化的行比查询另一个查询的结果要快。
查看将查询结果具体化到表的示例,然后在结果上使用 IN。我发现它比在另一种查询方法上使用 IN 更快,您可以阅读帖子的底部:http://www.ienablemuch.com/2012/05/recursive-cte-is-evil-and-cursor-is.html
例子:
SELECT distinct stringVal -- remove duplicates
into anotherTable
FROM TABLE2
where idTable2 = 5;
SELECT count(*)
FROM TABLE1 where stringVal in (select stringVal from anotherTable);
上面是在Sql Server和Postgresql上工作的,在其他RDBMS上可能是这样的:
create table anotherTable as
SELECT distinct stringVal -- remove duplicates
FROM TABLE2
where table2.idTable2 = 5;
select count(*)
from table1 where stringVal in (select stringVal from anotherTable)