Question

I have three tables:

ITEMDISPLAYCOuNTS *this table stores who displayed which posts and howmanytimes

postid, count, whodisplayedid

POSTS *this table stores who posted what?

postid, whopostedid

ASPNET_USERS

userid, username

What I want at the end is who displayed whose post, and how many times, with usernames, not userids:

OUTPUT

UserNameWhoDisplayed, UserNameWhosePost, Count

I wrote the following code, but it is not functioning properly.

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

Can anyone suggest any corrections?

Was it helpful?

Solution

I think you want something like this (changed your joins to proper ANSI ones):

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

OTHER TIPS

If I am understanding you correctly you do not need to perform any math in the query, since you have the count field in the ITEMDISPLAYCOuNTS table. So, I do believe this will work for you:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top