SQL 查询 'NOT IN' 与 'Join'
SQL query 'NOT IN' vs 'Join'
NOT IN 与使用 JOIN
SELECT COUNT(*)
FROM TBL_A AS A
WHERE A.MailDatId = 185208
AND SUBSTRING(A.PIMBRecord,3,3) NOT IN (SELECT B.ServiceTypeId FROM TBL_B AS B WHERE B.IsStandard = 1);
SELECT COUNT(*) FROM TBL_A AS A
LEFT JOIN (SELECT B.ServiceTypeId FROM TBL_B AS B WHERE B.IsStandard = 1) C
ON SUBSTRING(A.PIMBRecord,3,3) = C.ServiceTypeId
WHERE A.MailDatId = 185208
and C.ServiceTypeId IS NULL
我有上面两个查询,哪个更有效率?另外,如何测试 sql 服务器中查询的效率?
我实际上会为此推荐 not exists
:
select count(*)
from tbl_a a
where
a.mailDatId =
and not exists (
select 1
from tbl_b as b
where b.isStandard = 1 and b.serviceTypeId = substring(a.PIMBRecord,3,3)
)
理由:
NOT IN
不是空安全的,而 NOT EXISTS
是
JOIN
s 通常更适合您想要 return 来自另一个 table 的用例 - 这里不是这种情况
为了性能,您需要 tbl_b(serviceTypeId, isStandard)
上的索引
NOT IN 与使用 JOIN
SELECT COUNT(*)
FROM TBL_A AS A
WHERE A.MailDatId = 185208
AND SUBSTRING(A.PIMBRecord,3,3) NOT IN (SELECT B.ServiceTypeId FROM TBL_B AS B WHERE B.IsStandard = 1);
SELECT COUNT(*) FROM TBL_A AS A
LEFT JOIN (SELECT B.ServiceTypeId FROM TBL_B AS B WHERE B.IsStandard = 1) C
ON SUBSTRING(A.PIMBRecord,3,3) = C.ServiceTypeId
WHERE A.MailDatId = 185208
and C.ServiceTypeId IS NULL
我有上面两个查询,哪个更有效率?另外,如何测试 sql 服务器中查询的效率?
我实际上会为此推荐 not exists
:
select count(*)
from tbl_a a
where
a.mailDatId =
and not exists (
select 1
from tbl_b as b
where b.isStandard = 1 and b.serviceTypeId = substring(a.PIMBRecord,3,3)
)
理由:
NOT IN
不是空安全的,而NOT EXISTS
是JOIN
s 通常更适合您想要 return 来自另一个 table 的用例 - 这里不是这种情况
为了性能,您需要 tbl_b(serviceTypeId, isStandard)