我如何加入5个不同的表中的记录?

时间:2012-02-09 12:16:01

标签: mysql sql join

我想要检索所有课程及其相关数据。例如,课程所在的类别和课程的辅导员。我可以在一个Select语句中使用连接来检索我需要的数据吗?

我必须遵循架构

tbl_courses (id, name, description, tutor_id, date)
tbl_course_categories (id, course_id, category_id) 
tbl_categories (id, name, parent_id)
tbl_users (id, username, email, password)
tbl_tutors (id, first name, last name, user_id)

1 个答案:

答案 0 :(得分:1)

SELECT 
  c.NAME AS CourseName,
  ca.Name AS CategoryName,
  t.First_name + t.Last_name AS TutorName
FROM tbl_courses c
JOIN tbl_course_categories cc 
  ON cc.course_id = c.Id
JOIN tbl_categories ca
  ON ca.Id = cc.category_id
JOIN tbl_users u
  ON u.Id = c.tutor_id
JOIN tbl_tutor t 
  ON t.User_id = u.id

SELECT 
  c.NAME AS CourseName,
  GROUP_CONCAT(ca.Name+ ' ') AS Categories,
  t.First_name + t.Last_name AS TytorName
FROM tbl_courses c
JOIN tbl_course_categories cc 
  ON cc.course_id = c.Id
JOIN tbl_categories ca
  ON ca.Id = cc.category_id
JOIN tbl_users u
  ON u.Id = c.tutor_id
JOIN tbl_tutor t 
  ON t.User_id = u.id
GROUP BY c.NAME, t.First_name + t.Last_name