我有3张这样的表:
CREATE TABLE Main
(MainId INT PRIMARY KEY IDENTITY,
Name nvarchar(50))
CREATE TABLE Foo
(FooId INT PRIMARY KEY IDENTITY,
MainId int,
FooAnotherColumn int,
FOREIGN KEY (MainId) REFERENCES Main(MainId)
)
CREATE TABLE Bar
(BarId INT PRIMARY KEY IDENTITY,
MainId INT,
BarAnotherColumn INT,
FOREIGN KEY (MainId) REFERENCES Main(MainId)
)
我想从名字=某事的boo和bar表中计算。这是我到目前为止的查询。
DECLARE @fooCount int, @barCount int;
SELECT
@fooCount = (SELECT
(COUNT(*))
FROM Foo o
INNER JOIN Main s
ON o.MainId = s.MainId
WHERE s.Name = 'something')
SELECT
@barCount = (SELECT
(COUNT(*))
FROM Bar o
INNER JOIN Main s
ON o.MainId = s.MainId
WHERE s.Name = 'something')
SELECT
@fooCount + @barCount;
这可以优化吗?
答案 0 :(得分:1)
就性能而言,您的查询可能具有最佳计划。您可以将它们组合成一个查询:
SELECT f.foocount + b.barcount,
FROM (SELECT COUNT(*) as foocount,
FROM Foo o INNER JOIN
Main s
ON o.MainId = s.MainId
WHERE s.Name = 'something'
) f CROSS JOIN
(SELECT COUNT(*) as barcount
FROM Bar o INNER JOIN
Main s
ON o.MainId = s.MainId
WHERE s.Name = 'something'
) b;