首先,我正在处理4个表。
我有一个类表,它是与部分表的1> N关系,该表与具有1> N关系课程表。
所以要把它放在一起:
最后一个表是 activityLog ,当学生访问课程时,使用以下内容记录:
ActivityLog Row - > actorID(用户ID),classID,sectionID,lessonID
我想提取学生访问过的最后5个独特课程。我尝试使用DISTINCT和GROUP BY都没有成功。
每次都会返回相同的记录,而不是他们访问过的最新类。
使用GROUP BY
SELECT activityLog.actorID, activityLog.activityDate,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
GROUP BY activityLog.lessonID
ORDER BY activityLog.activityDate DESC
LIMIT 5
使用DISTINCT
SELECT DISTINCT activityLog.actorID,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
ORDER BY activityLog.activityDate DESC
LIMIT 5
我无法弄清楚为什么没有显示最新的记录。
答案 0 :(得分:2)
根据您的更改,这对您有何帮助?
SELECT activityLog.actorID, activityLog.activityDate,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
AND activityLog.activityDate = (SELECT MAX(activityDate) FROM activityLog AS lookup WHERE lessonID = activityLog.lessonID)
ORDER BY activityLog.activityDate DESC
LIMIT 5
根据您的描述,我不确定您使用LEFT JOIN
的原因,但为了以防万一,我已将其保留。
答案 1 :(得分:0)
请按以下方式尝试分组 GROUP BY activityLog.classID,activityLog.sectionID,activityLog.lessonID
我认为它会起作用,或者只是发送给我创建这些脚本我将创建该查询
答案 2 :(得分:0)
嗯,我希望ActivityLog中有一个日期时间......所以试试这个:
Select s.Name, c.ClassName
From Students s
left Join On Classes c
On c.ClassId In
(Select Distinct ClassId From Classes
Where (Select Count(Distinct ClassId) From Classes ic
Join ActivityLog l On l.UserId = s.UserId
And l.ClassId = c.ClassId
Where classId = c.ClassId
And activityDateTime > l.activityDateTime)
< 5)