下面是我的SQL代码:
select count(1)
from customers
where id in(
select custid
from accounts
where sid in(72,73,74,75,76,77,78,79)
)
and id not in(
select custid
from accounts
where sid in(80,81)
);
表格已正确编入索引。可以重写此代码以获得更好的性能吗?
答案 0 :(得分:3)
您也可以尝试EXISTS:
select count(1)
from customers c
where exists (
select 1
from accounts a
where sid in(72,73,74,75,76,77,78,79)
and a.custid = c.custid
)
and not exists (
select 1
from accounts a
where sid in(80,81)
and a.custid = c.custid
);
这可能会有帮助,请阅读:Difference between EXISTS and IN in SQL?
答案 1 :(得分:0)
加入你的桌子,而不是使用2个subquerys。
SELECT count(1)
FROM customers c
INNER JOIN accounts a ON c.id = a.sid
WHERE id IN (72, 73, 74, 75, 76, 77, 78, 79)
答案 2 :(得分:0)
减号查询可能更有效。像这样:
SELECT count(1)
FROM
(
SELECT c.id
FROM customers c
INNER JOIN accounts a ON c.id = a.sid
WHERE id IN (72, 73, 74, 75, 76, 77, 78, 79)
MINUS
SELECT c.id
FROM customers c
INNER JOIN accounts a ON c.id = a.sid
WHERE id IN (80,81)
)