这是moodle中的一个查询,可以获得课程中的校友身份。 “X”表示用户已注册,空未注册。 我们必须为每个课程添加子查询... 任何人都可以帮忙做更好的查询吗?
SELECT
user1.firstname AS Firstname,
user1.lastname AS Lastname,
user1.email AS Email,
if (exists( SELECT
ue.id
FROM mdl_user_enrolments AS ue
JOIN mdl_enrol AS en ON en.id = ue.enrolid
JOIN mdl_course AS course ON course.id = en.courseid
WHERE user1.id = ue.userid AND course.id = '1'), 'X', '') as "Enrolled Course One"
FROM mdl_user AS user1
LEFT JOIN mdl_user_enrolments AS ue ON ue.userid = user1.id
LEFT JOIN mdl_enrol AS en ON en.id = ue.enrolid
LEFT JOIN mdl_course AS course ON course.id = en.courseid
[...]
WHERE user1.deleted='0'
答案 0 :(得分:1)
你可以尝试这样的事情但是如果你有很多用户和课程需要很长时间来处理
SELECT CONCAT(u.id, '_', c.id) AS uniqueid,
u.id AS userid,
u.firstname,
u.lastname,
u.email,
MAX(CASE WHEN ue.id IS NULL THEN '' ELSE 'X' END) AS enrolled,
c.id AS courseid,
c.fullname AS coursename
FROM mdl_user u
CROSS JOIN mdl_course c
LEFT JOIN mdl_enrol e ON e.courseid = c.id
LEFT JOIN mdl_user_enrolments ue ON u.id = ue.userid AND ue.enrolid = e.id
WHERE u.deleted = 0
GROUP BY u.id, c.id