我从两个不同的查询创建的查询结果不会返回相同的结果。
查询A
SELECT
c.fullname Course,
u.firstname First,
u.lastname Last,
u.id ID,
u.institution Company
FROM (mdl_scorm_scoes_track AS st)
JOIN mdl_user AS u ON st.userid=u.id
JOIN mdl_scorm AS sc ON sc.id=st.scormid
JOIN mdl_course AS c ON c.id=sc.course
Join mdl_user_enrolments AS uenr ON uenr.userid=u.id
Join mdl_enrol AS enr ON enr.id=uenr.enrolid
WHERE (
(st.value='incomplete' OR st.value='not attempted')
AND DATEDIFF(NOW(), FROM_UNIXTIME(uenr.timecreated)>60)
ORDER BY c.fullname, u.lastname,u.firstname, u.id
查询B
SELECT
c.fullname AS Course,
u.firstname AS Firstname,
u.lastname AS Lastname,
u.id AS ID,
u.institution AS Company,
IF (u.lastaccess = 0,'never',
DATE_FORMAT(FROM_UNIXTIME(u.lastaccess),'%Y-%m-%d')) AS dLastAccess
,(SELECT DATE_FORMAT(FROM_UNIXTIME(timeaccess),'%Y-%m-%d') FROM mdl_user_lastaccess WHERE userid=u.id AND courseid=c.id) AS CourseLastAccess
FROM mdl_user_enrolments AS ue
JOIN mdl_enrol AS e ON e.id = ue.enrolid
JOIN mdl_course AS c ON c.id = e.courseid
JOIN mdl_user AS u ON u.id = ue.userid
LEFT JOIN mdl_user_lastaccess AS ul ON ul.userid = u.id
WHERE ul.timeaccess IS NULL AND (DATEDIFF(NOW(), FROM_UNIXTIME(ue.timecreated))>60)
ORDER BY u.id, c.fullname
我已将它们合并到Query C
中SELECT
c.fullname AS Course,
u.firstname AS Firstname,
u.lastname AS Lastname,
u.id AS IDNumber,
u.institution AS Institution,
IF (u.lastaccess = 0,'never',
DATE_FORMAT(FROM_UNIXTIME(u.lastaccess),'%Y-%m-%d')) AS dLastAccess
,(SELECT DATE_FORMAT(FROM_UNIXTIME(timeaccess),'%Y-%m-%d') FROM mdl_user_lastaccess WHERE userid=u.id AND courseid=c.id) AS CourseLastAccess
FROM mdl_user_enrolments AS ue
JOIN mdl_enrol AS e ON e.id = ue.enrolid
JOIN mdl_course AS c ON c.id = e.courseid
JOIN mdl_user AS u ON u.id = ue.userid
LEFT JOIN mdl_user_lastaccess AS ul ON ul.userid = u.id
WHERE (ul.timeaccess IS NULL OR ue.userid IN
(SELECT u.id
FROM (mdl_scorm_scoes_track AS st)
JOIN mdl_scorm AS sc ON sc.id=st.scormid
WHERE c.id=sc.course AND st.userid=u.id AND (st.value='incomplete' OR st.value='not attempted')
)
)AND (DATEDIFF(NOW(), FROM_UNIXTIME(ue.timecreated))>60)
ORDER BY c.fullname, u.lastname,u.firstname
我没有在查询C中找到我的逻辑不正确的地方。查询C添加了A或B找不到的错误记录,并在几种情况下复制了条目。
我想要一些关于我将2合并的逻辑误入歧途的指示。
我在这篇文章中修复了逗号,实际的查询确实有这些逗号。
我的目的是列出所有已注册课程但在指定时间范围内,尚未登录系统,访问课程并最终未完成课程活动的用户。
所以我要找的逻辑是: 如果用户未在60天内登录 - 显示名称 如果已登录但未在60天内访问该课程 - 显示名称 如果已登录并已访问课程但尚未完成课程活动 - 显示名称
查询A会列出所有启动活动但尚未在60天内完成的用户 查询B列出了所有未在60天内登录或访问过课程的用户
在尝试组合2个查询以满足所有3个条件时,我遇到了问题。我第一次尝试使用UNION但无法使其工作。
答案 0 :(得分:0)
您不会在两个查询中选择相同的世界。查询A有6个表从中选择,查询B有5个(它缺少mdl_scorm表),查询C有5个表,查询B有。所以现在你的查询范围已经改变了。这个额外的表可能已经消除了连接中的行,这些行现在出现在查询C中,用于选择A.
我会查询查询A,查询中缺少mdl_scorm表,您可能会有不同的结果大小。
将其视为
从TABLES中选择COLUMNS,其中FILTERS;对于两个查询,TABLES(数据世界)需要相同才能加入COLUMNS和FILTERS(扩展选择和限制结果)