这取决于您的 SQL 实现。
SQL 是声明性的,由优化器根据逻辑规范构建物理计划。SQL Server 可以去关联这个子查询并变成一个OUTER JOIN
CREATE TABLE A(id INT PRIMARY KEY, col1 INT, col2 INT, col3 INT)
CREATE TABLE B(aid INT)
CREATE CLUSTERED INDEX ix ON B(aid)
/*Fool optimiser into thinking tables aren't empty*/
update statistics A with rowcount = 1000000, pagecount = 100000
update statistics B with rowcount = 1000000, pagecount = 100000
SELECT col1,
col2,
col3,
(SELECT count( B.aid)
FROM B
WHERE B.aid = A.id) AS col4
FROM A
DROP TABLE A, B
给出计划
基本上是一样的
SELECT col1,
col2,
col3,
Cnt
FROM (SELECT COUNT(aid) AS Cnt,
aid
FROM B
GROUP BY aid) T
RIGHT OUTER JOIN A
ON A.id = T.aid
子查询在逻辑上表示为RIGHT OUTER JOIN
与MERGE JOIN
物理实现一样。合并连接处理每个输入一次,而不是嵌套循环连接的逐行行为。