Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 help with heavy query

Author  Topic 

mike123
Master Smack Fu Yak Hacker

1462 Posts

Posted - 2006-06-07 : 22:36:58
Hi,

I have a users table tblUserDetails in which I am trying to get the COUNT(*) of "mail" or "comments" they have. I only need to bring rows that have either InstantMessageCount or MessageCount above 0.

tblUserDetails
tblInstantMessage
tblMessage

What's the best way to do this? I have tried writing a query like this below, however its painfully slow. (20 seconds for the first 10k rows). There are about 500k rows in tblUserDetails.


Maybe this query should originate from either tblInstantMessage or tblMessage ?? I think this would eliminate all the users being brought back with 0 IMcount AND 0 MailCount .. I don't want these records brought back, they must have at least 1 in either column.

One of the many other approaches I've considered, is to insert rows in another logging table everytime someone gets "mail" or "comments". I think that this is not very normalized and there should be a cleaner approach ?


Kinda hard to explain, but hopefully that makes some sense. Many thanks for any guidance!!

mike123



SELECT top 10000 userID, nameOnline,lastLoggedIn,emailAddress,

(select count(*) FROM tblInstantMessage IM WHERE checked = 0 AND date < UD.lastLoggedIN AND messageToID = UD.userID AND IM.date > dateAdd(dd,-1,getDate())) as IMCount,
(select count(*) FROM tblMessage M WHERE checked = 0 AND date < UD.lastLoggedIN and messageTo = UD.userID and M.date > dateAdd(dd,-1,getDate())) as MailCount


FROM tblUserDetails UD


khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-06-07 : 23:22:02
Can you post the table structure ?


KH

Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-06-08 : 00:07:31
Give this a try. Note I did not test the query.


select u.userID, u.nameOnline, u.lastLoggedIn, u.emailAddress,
isnull(a.IMCount, 0) as IMCount,
isnull(b.MailCount, 0) as MailCount
from tblUserDetails u
left join
(
select UD.userID, count(*) as IMCount
from tblUserDetails UD inner join tblInstantMessage IM
on IM.messageToID = UD.userID
and IM.checked = 0
and IM.Date < UD.lastLoggedIN
and IM.Date > dateadd(day, -1, getdate())
group by UD.userID
having count(*) > 0

) a
on u.userID = a.userID
left join
(
select UD.userID, count(*) as MailCount
from tblUserDetails UD inner join tblMessage M
on M.messageTo = UD.userID
and M.checked = 0
and M.Date < UD.lastLoggedIN
and M.Date > dateadd(day, -1, getdate())
group by UD.userID
having count(*) > 0

) b
on a.userID = b.userID
where a.IMCount is not null
or b.MailCount is not null



KH

Go to Top of Page
   

- Advertisement -