许多子连接在子查询上,需要一些方法来提高性能

时间:2015-04-21 18:13:59

标签: sql sql-server

下面是我的查询示例。我最多只有大约10个这些连接/子查询都具有基本相同的格式,但具有不同的连接和where子句。

SELECT DISTINCT mytable.label, tableA.counter, tableB.counter
FROM mytable
LEFT JOIN 
    (SELECT COUNT(id) as counter, label
        FROM mytable
        ...joins...
        ...where...
        GROUP BY label) tableA 
    ON tableA.label=mytable.label
LEFT JOIN
    (SELECT COUNT(id) as counter, label
        FROM mytable
        ...joins...
        ...where...
        GROUP BY label) tableB 
    ON tableB.label=mytable.label
...

这需要大约2-4秒,这是一个高流量的页面,所以这种速度不够好。任何人都可以推荐一种提高性能的方法吗?

2 个答案:

答案 0 :(得分:2)

此处无需GROUP,因为您只返回1个值。尝试这样的子查询方法:

SELECT DISTINCT T.label,
  (SELECT COUNT(id) as counter FROM tableA A WHERE A.blah = T.blah) as AValue,
  (SELECT COUNT(id) as counter FROM tableB B WHERE B.blah = T.blah) as BValue
FROM mytable T

答案 1 :(得分:0)

除了Jon Tirjan的解决方案之外,我还会使用UNIONPIVOT表分享另一个解决方案。

SELECT [A], [B]
FROM (
    SELECT 'A' AS TableName, COUNT(id) as counter
    FROM tableA 
    UNION ALL
    SELECT 'B' AS TableName, COUNT(id) as counter
    FROM tableB
) AS DT
PIVOT(SUM(counter) FOR TableName IN([A], [B])) AS PVT