Hello Guys我和我有以下关系表,
我正在编写我的存储过程中的嵌套查询
. Select useremail,fullname,city,[state], allowAlerts,allowLetters,aboutMe,avatar,dateregistered,
(Select COUNT(*) from blog_info where blog_info.userId = @userId)as blogCount,
(Select count(*) from blog_info where blog_info.isfeatured = 1 AND blog_info.userId = @userId)as featuredCount,
(Select COUNT(*) from blog_comments where blog_comments.userId = @userId)as commentsCount,
(Select COUNT(*) from forum where forum.createdby = @userId) as forumCount,
(Select COUNT(*) from forumresponse where forumresponse.userId = @userId)as responseCount
from user_info where _id = @userId.
我想用这个连接的查询替换这个嵌套的查询。
请求帮助我实现这一目标。
先谢谢
答案 0 :(得分:1)
您是否尝试过粘贴该查询并在其中突出显示该查询 查询编辑器,然后单击查询设计器工具栏按钮? Management Studio将在Query Designer中打开查询,并根据连接重写它。
答案 1 :(得分:1)
另一种方法是运行所有count子查询并存储在单独的SP变量中。您是否尝试过在缓存等方面查看它是否比多个子查询更有效?
答案 2 :(得分:1)
select
u.useremail,
u.fullname,
u.city,
u.[state],
u.allowAlerts,
u.allowLetters,
u.aboutMe,
u.avatar,
u.dateregistered,
isnull(ub.blogCount,0) blogCount,
uf.featuredCount,
uf2.forumCount,
ur.responseCount
from
user_info u
left outer join
(select userid, count(*) blogCount from blog_info group by userid) ub on ub.userid = u._id
(等等,为您最初的每个子查询执行类似的连接)
where
u._id = @userId
抱歉无用的格式化!
注意:查询引擎可能足够聪明,可以对两个查询使用相同的执行计划,因此您不一定会看到改进