SQL帮助 - 按用户ID过滤

时间:2011-01-05 16:25:47

标签: sql relational-database

SELECT     projectID, urlID, COUNT(1) AS totalClicks, projectPage,
                          (SELECT     COUNT(1)
                            FROM          tblStatSessionRoutes, tblStatSessions
                            WHERE      tblStatSessionRoutes.statSessionID = tblStatSessions.ID AND tblStatSessions.projectID = tblAdClicks.projectID AND 
                                                   (tblStatSessionRoutes.leftPageID = tblAdClicks.projectPage OR
                                                   tblStatSessionRoutes.rightPageID = tblAdClicks.projectPage)) AS totalViews
FROM         tblAdClicks
GROUP BY projectID, urlID, projectPage
ORDER BY projectID, urlID

tblProjects有一个字段UserID,我需要这个查询只显示项目有userID = 5的记录,以便不显示所有用户的所有项目的所有统计数据

2 个答案:

答案 0 :(得分:2)

天真:

SELECT     projectID, urlID, COUNT(1) AS totalClicks, projectPage,
                          (SELECT     COUNT(1)
                            FROM          tblStatSessionRoutes, tblStatSessions
                            WHERE      tblStatSessionRoutes.statSessionID = tblStatSessions.ID AND tblStatSessions.projectID = tblAdClicks.projectID AND 
                                                   (tblStatSessionRoutes.leftPageID = tblAdClicks.projectPage OR
                                                   tblStatSessionRoutes.rightPageID = tblAdClicks.projectPage)) AS totalViews
FROM         tblAdClicks
WHERE projectID IN (SELECT projectID FROM tblProjects WHERE userID = 5)
GROUP BY projectID, urlID, projectPage
ORDER BY projectID, urlID

但是加入可能会更好。与往常一样,检查您的执行计划

答案 1 :(得分:1)

好吧,我不知道您拥有的数据的结构,但如果没有别的,您可以随时加入以下子查询:

select projectID from tblProjects where userID=5

关于你应该用于连接的列,我真的不能告诉你,因为我不知道你的数据的具体细节。