从相关表中获取记录计数的最有效方法?

时间:2009-12-04 13:28:42

标签: sql sql-server join

我有一个存储过程,其中包含select语句:

select 
    (select Count(FaqId) from faq_read_stats where faqid = Faq.Id) as ReadCount,
    Faq.*
from Faq 
where Faq.Show = 1 and Faq.Active = 1

这给了我想要的结果,但似乎有可能没有针对SQL Server进行优化的临时选择计数。

我尝试在faq_read_stats表上进行内连接,但是这并没有产生正确的结果(它遗漏了faq记录,在faq_read_stats中没有记录,而我上面输入的sql正确地显示了0的计数)。

是否有更有效的方法来获取此数据?

4 个答案:

答案 0 :(得分:4)

你需要尝试比较,但另一种选择是:

SELECT ISNULL(x.ReadCount, 0) AS ReadCount, f.*
FROM Faq f
    LEFT JOIN
    (
        SELECT faqid, COUNT(faqid) AS ReadCount
        FROM faq_read_stats
        GROUP BY faqid
    ) x ON f.id = x.faqid
WHERE f.Show = 1 AND f.Active = 1

答案 1 :(得分:1)

使用LEFT OUTER JOIN:

而不是使用INNER JOIN
SELECT
     COUNT(*) AS read_count,
     FAQ.col_1,
     FAQ.col_2,
     FAQ.col_3,
     ...
FROM
     FAQ
LEFT OUTER JOIN Faq_Read_Stats FRS ON
     FRS.faq_id = FAQ.faq_id
WHERE
     FAQ.show = 1 AND
     FAQ.active = 1
GROUP BY
     FAQ.col_1,
     FAQ.col_2,
     FAQ.col_3,
     ...

答案 2 :(得分:0)

这样的事情会起作用还是你已经尝试过的?

SELECT SUM(CASE WHEN (faq_read_stats.FaqId = Faq.Id) THEN 1 ELSE 0 END) AS ReadCount, Faq.*
FROM Faq INNER JOIN faq_read_stats ON faq_read_stats.FaqId = Faq.Id
WHERE Faq.Show = 1 and Faq.Active = 1

詹姆斯

答案 3 :(得分:0)

在调整查询时,我总是考虑“分而治之”的方法。

我敢打赌下面的代码会得到最好的结果:

select FaqID, count(*) as ReadCount
into #cnt
from faq_read_stats
group by FaqID
go

select 
  #cnt.ReadCount,
  Faq.*
from
  Faq
    left outer join #cnt
    on cnt.FaqID = Faq.FaqID
where Faq.Show = 1 and Faq.Active = 1
go

drop table #cnt
go

这种方法使其更具“人类可读性”,并未引入“虚假最优”计划。