穆德尔数据库的几个表之间的条件连接

时间:2019-03-19 14:25:00

标签: mysql join mysqli conditional moodle

我需要根据一些先前表的输出在几个表之间创建一个联接查询。我正在尝试使用case when statement如下,但显示错误!任何帮助表示赞赏

SELECT completion.userid, completion. coursemoduleid, completion. timemodified, 
module.course, user. idnumber as student_id, m.name as module_name, activity.name as activity_name
FROM `mdl_course_modules_completion` as completion

join mdl_course_modules as module 
on completion. coursemoduleid = module.id

join mdl_user as user on user.id = completion.userid

join mdl_modules as m on completion. coursemoduleid = m.id

join 
CASE WHEN module_name = 'assign'THEN 'mdl_assign'
     WHEN module_name = 'assignment'  THEN 'mdl_assignment'
     ELSE "quiz"
END AS activity

on activity.id = m.id LIMIT 0, 30

enter image description here

2 个答案:

答案 0 :(得分:0)

There is no such thing as "conditional join". Instead you can use two LEFT JOINs and COALESCE():

SELECT completion.userid,
  ...
  COALESCE(activity1.name, activity2.name) as activity_name -- SELECT first non NULL value
FROM `mdl_course_modules_completion` as completion
...
LEFT JOIN mdl_assign activity1
  ON  activity1.id = m.id    -- JOIN condition
  AND module_name = 'assign' -- CASE condition
LEFT JOIN mdl_assignment activity2
  ON  activity2.id = m.id        -- JOIN condition
  AND module_name = 'assignment' -- CASE condition

答案 1 :(得分:0)

希望这对您有帮助-

SELECT completion.userid, completion. coursemoduleid, completion. timemodified, 
module.course, user. idnumber as student_id, m.name as module_name,(CASE WHEN (a.name != '') THEN a.name ELSE (CASE WHEN (ass.name != '') THEN ass.name ELSE q.name END) END) as activity_name
FROM `mdl_course_modules_completion` as completion
join mdl_course_modules as module 
on completion. coursemoduleid = module.id
join mdl_user as user on user.id = completion.userid
join mdl_modules as m on completion. coursemoduleid = m.id
left join mdl_assign as a on a.id = m.id
left join mdl_assignment as ass on ass.id = m.id
left join mdl_quiz as q on q.id = m.id
where m.name in ('assign','assignment','quiz')
LIMIT 0, 30