sql选择3个表中的查询

时间:2013-10-11 20:08:43

标签: sql select join multiple-tables

我有三张桌子:

ITEMDISPLAYCOuNTS *此表存储显示哪些帖子和时间的人

postid,count,whodisplayedid

POSTS *此表存储了谁发布了什么?

postid,whopostedid

ASPNET_USERS

userid,用户名

我最终想要的是谁用用户名显示了哪些帖子,多少次,而不是用户名:

输出

UserNameWhoDisplayed,UserNameWhosePost,Count

我编写了以下代码,但它无法正常运行。

SELECT u1.UserName, u2.UserName, ItemDisplayCounts.Count
FROM ItemDisplayCounts AS i, Posts AS p, aspnet_Users AS u1, aspnet_Users AS u2
WHERE p.UserId = u2.UserId AND i.UserId = u1.UserId AND i.PostId = p.PostId

有人可以建议任何更正吗?

2 个答案:

答案 0 :(得分:3)

我认为你想要这样的东西(将你的连接改为适当的ANSI连接):

select
    iu.UserName as UserNameWhoDisplayed,
    pu.UserName as UserNameWhosePost,
    sum(i.Count) as [Count]
from ItemDisplayCounts as i
    inner join aspnet_Users as iu on iu.userid = i.whodisplayedid
    inner join posts as p on p.postid = i.postid
    inner join aspnet_Users as pu on pu.userid = p.whopostedid
group by
    iu.UserName,
    pu.UserName

答案 1 :(得分:1)

如果我理解正确,您不需要在查询中执行任何数学运算,因为count表中有ITEMDISPLAYCOuNTS字段。所以,我相信这对你有用:

SELECT U2.username AS UserNameWhoDisplayed, 
       U1.username AS UserNameWhosePost, 
       ID.[Count]
FROM ((POSTS AS P 
       INNER JOIN ASPNET_USERS AS U1 ON P.whopostedid = U1.userid) 
       INNER JOIN ITEMDISPLAYCOuNTS AS ID ON P.postid = ID.postid) 
       INNER JOIN ASPNET_USERS AS U2 ON ID.whodisplayedid = U2.userid