mysql select with joins and conditions语句

vnjpjtjt  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(374)

我有三张table

  1. TABLE `courses` (
  2. id int NOT NULL UNIQUE AUTO_INCREMENT,
  3. title varchar(50) NOT NULL UNIQUE,
  4. duration int NOT NULL,
  5. theme varchar(50) NOT NULL,
  6. students_quantity int NOT NULL,
  7. PRIMARY KEY (id)
  8. );
  9. TABLE `users` (
  10. id int NOT NULL UNIQUE AUTO_INCREMENT,
  11. name varchar(50) NOT NULL,
  12. email varchar(50) NOT NULL UNIQUE,
  13. password varchar(50) NOT NULL,
  14. status varchar(20) NOT NULL,
  15. role_id int NOT NULL,
  16. PRIMARY KEY (id),
  17. FOREIGN KEY (role_id) REFERENCES `roles` (id)
  18. );
  19. TABLE `teachers_courses` (
  20. teacher_id int NOT NULL,
  21. course_id int NOT NULL,
  22. PRIMARY KEY (teacher_id, course_id),
  23. FOREIGN KEY (teacher_id) REFERENCES `users` (id),
  24. FOREIGN KEY (course_id) REFERENCES `courses` (id)
  25. ON DELETE CASCADE
  26. ON UPDATE CASCADE
  27. );

我怎样才能拿到课程呢 users.name AS teacher 如果我没有 course_id 以及 teacher_id 为了这门课 teachers_courses 我一个也不进去 teacher ?

nwsw7zdq

nwsw7zdq1#

使用 JOIN 按主键-外键路径组合数据。功能 coalesce() 如果第一个参数的计算结果为 NULL .

  1. select c.*, coalesce(u.name, 'none') as teacher
  2. from courses c
  3. left join teachers_courses tc on c.id = tc.course_id
  4. left join users u on tc.teacher_id = u.id
  5. order by c.id

因为每门课可以有多个老师,所以 'none' 如果一门课没有老师(甚至连一个都没有)的话,教师的价值观就是这样。如果有一个以上的教师,那么输出中的行数将与每门课程的教师数相同,因此我将其包括在内 ORDER BY 正确排序结果。
如果您只需要查看一个课程的数据,请包含如下where条件:

  1. -- ... Above SQL here ...
  2. WHERE c.id = ?

相关问题