SQL计数来自两个不同表的行,其中两个表具有来自完全不同的表的相同外键

时间:2014-12-04 02:46:45

标签: sql sql-server

我有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;

这可以优化吗?

1 个答案:

答案 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;