MySql SELECT with Joins and conditions 语句
MySql SELECT with Joins and conditions statement
我有三张表
TABLE `courses` (
id int NOT NULL UNIQUE AUTO_INCREMENT,
title varchar(50) NOT NULL UNIQUE,
duration int NOT NULL,
theme varchar(50) NOT NULL,
students_quantity int NOT NULL,
PRIMARY KEY (id)
);
TABLE `users` (
id int NOT NULL UNIQUE AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(50) NOT NULL UNIQUE,
password varchar(50) NOT NULL,
status varchar(20) NOT NULL,
role_id int NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (role_id) REFERENCES `roles` (id)
);
TABLE `teachers_courses` (
teacher_id int NOT NULL,
course_id int NOT NULL,
PRIMARY KEY (teacher_id, course_id),
FOREIGN KEY (teacher_id) REFERENCES `users` (id),
FOREIGN KEY (course_id) REFERENCES `courses` (id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
如何获取课程。* 和 users.name AS teacher
这门课程,如果我没有 course_id
和 teacher_id
这门课程的 teachers_courses
我'我会在 teacher
?
中得到 'none'
使用JOIN
按照主键-外键路径合并您的数据。
函数 coalesce()
将 return 第二个参数,如果第一个参数的计算结果为 NULL
.
select c.*, coalesce(u.name, 'none') as teacher
from courses c
left join teachers_courses tc on c.id = tc.course_id
left join users u on tc.teacher_id = u.id
order by c.id
由于每门课程可以有多位教师,因此您将获得 'none'
作为教师值的唯一情况是没有为一门课程分配教师(甚至没有)。如果有不止一位老师,输出中的行数将与每门课程的老师数一样多,因此我包含 ORDER BY
以正确排序结果。
如果您只需要查看一门课程的数据,请包含如下 WHERE 条件:
-- ... Above SQL here ...
WHERE c.id = ?
我有三张表
TABLE `courses` (
id int NOT NULL UNIQUE AUTO_INCREMENT,
title varchar(50) NOT NULL UNIQUE,
duration int NOT NULL,
theme varchar(50) NOT NULL,
students_quantity int NOT NULL,
PRIMARY KEY (id)
);
TABLE `users` (
id int NOT NULL UNIQUE AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(50) NOT NULL UNIQUE,
password varchar(50) NOT NULL,
status varchar(20) NOT NULL,
role_id int NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (role_id) REFERENCES `roles` (id)
);
TABLE `teachers_courses` (
teacher_id int NOT NULL,
course_id int NOT NULL,
PRIMARY KEY (teacher_id, course_id),
FOREIGN KEY (teacher_id) REFERENCES `users` (id),
FOREIGN KEY (course_id) REFERENCES `courses` (id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
如何获取课程。* 和 users.name AS teacher
这门课程,如果我没有 course_id
和 teacher_id
这门课程的 teachers_courses
我'我会在 teacher
?
使用JOIN
按照主键-外键路径合并您的数据。
函数 coalesce()
将 return 第二个参数,如果第一个参数的计算结果为 NULL
.
select c.*, coalesce(u.name, 'none') as teacher
from courses c
left join teachers_courses tc on c.id = tc.course_id
left join users u on tc.teacher_id = u.id
order by c.id
由于每门课程可以有多位教师,因此您将获得 'none'
作为教师值的唯一情况是没有为一门课程分配教师(甚至没有)。如果有不止一位老师,输出中的行数将与每门课程的老师数一样多,因此我包含 ORDER BY
以正确排序结果。
如果您只需要查看一门课程的数据,请包含如下 WHERE 条件:
-- ... Above SQL here ...
WHERE c.id = ?