SQL Server 2005 RIGHT OUTER JOIN 不起作用
我正在查找特定课程的访问日志。我需要显示所有课程,即使它们不存在于日志表中。因此,外部连接......但在尝试(大概)LEFT OUTER
、RIGHT OUTER
、INNER
的所有变体和放置之后SQL 代码中的表,我无法得到结果。
这是我正在运行的内容:
SELECT (a.first_name+' '+a.last_name) instructor,
c.course_id,
COUNT(l.access_date) course_logins,
a.logins system_logins,
MAX(l.access_date) last_course_login,
a.last_login last_system_login
FROM lsn_logs l RIGHT OUTER JOIN courses c ON l.course_id = c.course_id,
accounts a
WHERE l.object_id = 'LOGIN'
AND c.course_type = 'COURSE'
AND c.course_id NOT LIKE '%TEST%'
AND a.account_rights > 2
AND l.user_id = a.username
AND ((a.first_name+' '+a.last_name) = c.instructor)
GROUP BY c.course_id,
a.first_name,
a.last_name,
a.last_login,
a.logins,
c.instructor
ORDER BY a.last_name,
a.first_name,
c.course_id,
course_logins DESC
WHERE
子句中是否有某些内容阻止我获取 lsn_logs 中不存在的 course_id?这是我加入桌子的方式吗?
简而言之,我想要所有的 course_id,无论它们是否存在于 lsn_logs 中。
I'm looking up access logs for specific courses. I need to show all the courses even if they don't exist in the logs table. Hence the outer join.... but after trying (presumably) all of the variations of LEFT OUTER
, RIGHT OUTER
, INNER
and placement of the tables within the SQL code, I couldn't get my result.
Here's what I am running:
SELECT (a.first_name+' '+a.last_name) instructor,
c.course_id,
COUNT(l.access_date) course_logins,
a.logins system_logins,
MAX(l.access_date) last_course_login,
a.last_login last_system_login
FROM lsn_logs l RIGHT OUTER JOIN courses c ON l.course_id = c.course_id,
accounts a
WHERE l.object_id = 'LOGIN'
AND c.course_type = 'COURSE'
AND c.course_id NOT LIKE '%TEST%'
AND a.account_rights > 2
AND l.user_id = a.username
AND ((a.first_name+' '+a.last_name) = c.instructor)
GROUP BY c.course_id,
a.first_name,
a.last_name,
a.last_login,
a.logins,
c.instructor
ORDER BY a.last_name,
a.first_name,
c.course_id,
course_logins DESC
Is it something in the WHERE
clause that's preventing me from getting course_id's that don't exist in lsn_logs? Is it the way I'm joining the tables?
Again, in short, I want all course_id's regardless of their existence in lsn_logs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的。
您可以在
WHERE
子句中使用相等条件,有效地过滤掉OUTER JOIN
生成的NULL
行。更新:
Yes, it is.
You use equality conditions in your
WHERE
clause that effectively filter out theNULL
rows generated by theOUTER JOIN
.Update:
要扩展 Quassnoi 的好答案,为了使外部连接正常工作,您可以更改:
到:
To expand on Quassnoi's good answer, for the outer join to work you could change:
To:
SQL Server 2005 RIGHT OUTER JOIN 确实有效! :)
那么以下内容怎么样(我做了一些假设)?:
删除
并更改连接
并为 lsn_logs 和帐户字段添加一些空检查,例如:
The SQL Server 2005 RIGHT OUTER JOIN certainly works! :)
What about the following (I've made some assumptions)?:
remove
and change the joins to
and add some null checks for lsn_logs and accounts fields, such as:
这最终起作用了
Joe R 建议的空检查解决了 Quassnoi 提到的问题
This ended up working
The null checks that Joe R suggested took care of the problem that Quassnoi mentioned