我正在使用Moodle数据库查询学生和老师为他们注册的相关课程所做的最新论坛帖子。
以下是我需要加入的表格及其所持有的解释:
mdl_forum_posts =“所有帖子都存储在此表中”
mdl_forum_discussions =“论坛由讨论组成” mdl_user =“关于用户存储的信息”
mdl_log =“系统的每个用户的活动都是它,登录 - 添加帖子”
mdl_user_enrolments =“参与课程的用户”
mdl_enrol =“mdl_course中使用的注册插件实例”
mdl_course =“系统中可用的课程”
这是我的问题:
SELECT l.time AS TimeofPost, l.action as Action, usr.id as UserID,
usr.firstname,usr.lastname, c.id as CourseID , c.fullname,
c.idnumber, fd.name, fd.timemodified as CreatedOn, fp.created,
fp.modified, fp.subject, fp.message
FROM mdl_forum_posts fp
LEFT JOIN mdl_forum_discussions fd ON fp.discussion = fd.id
LEFT JOIN mdl_user usr ON fp.userid = usr.id
LEFT JOIN mdl_log l ON usr.id = l.userid
LEFT JOIN mdl_user_enrolments ue ON usr.id = ue.userid
LEFT JOIN mdl_enrol e ON ue.enrolid = e.id
LEFT JOIN mdl_course c ON e.courseid = c.id
WHERE (action = 'add post' OR action = 'add discussion')
我遇到的问题是我得到了重复的结果。
答案 0 :(得分:2)
您目前正在将mdl_forum_posts链接到用户ID上的mdl_log。
这意味着特定用户的每个记录的操作记录都将链接到该用户发布的每个帖子(而不是将特定帖子链接到发布操作的日志)。
答案 1 :(得分:1)
无需使用日志表 - 已添加帖子并具有时间戳的事实就是您所需要的。另外,除非你期望空值,否则你真的不想使用LEFT JOIN,这里绝不应该这样。我已经离开了注册表的链接,这样如果有任何学生没有注册,他们就不会出现,但这不是必需的。
您正在获得重复项,因为每个论坛帖子都有多个匹配项,例如每个课程的注册表有很多实例。这个查询确保你只需要有东西。
SELECT fp.id,
usr.id as UserID,
usr.firstname,
usr.lastname,
c.id as CourseID,
c.fullname,
c.idnumber,
fd.name,
fd.timemodified as DiscussionCreatedOn,
fp.created AS TimeofPost,
fp.modified,
fp.subject,
fp.message
FROM mdl_forum_posts fp
INNER JOIN mdl_forum_discussions fd ON fp.discussion = fd.id
INNER JOIN mdl_forum f ON f.id = fd.forum
INNER JOIN mdl_course c ON f.course = c.id
INNER JOIN mdl_user usr ON fp.userid = usr.id
WHERE EXISTS (SELECT 1
FROM mdl_user_enrolments ue
INNER JOIN mdl_enrol e ON ue.enrolid = e.id
WHERE usr.id = ue.userid
AND e.courseid = f.course)
答案 2 :(得分:0)
SELECT DISTINCT l.time AS TimeofPost, l.action as Action, usr.id as UserID, usr.firstname, usr.lastname, c.id as CourseID , c.fullname, c.idnumber, fd.name, fd.timemodified as CreatedOn, fp.created, fp.modified, fp.subject, fp.message
“单词”DISTINCT可以帮助你