一、创建数据库,创建表结构
CREATE DATABASE Test_sub DEFAULT CHARACTER SET utf8;
USE Test_sub;
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT, -- 学号 id
NAME VARCHAR(10) -- 姓名 name
);
CREATE TABLE course(
id INT PRIMARY KEY AUTO_INCREMENT, -- 课程号 id
NAME VARCHAR(10) -- 课程名 name
);
CREATE TABLE sc(
student_id INT,
course_id INT,
PRIMARY KEY(student_id, course_id),
CONSTRAINT student_fk FOREIGN KEY(student_id) REFERENCES student(id) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT course_fk FOREIGN KEY(course_id) REFERENCES course(id) ON UPDATE CASCADE ON DELETE CASCADE
);
二、插入数据
INSERT INTO student(NAME) VALUES
('aaa'), ('bbb'), ('ccc'), ('ddd');
INSERT INTO course(NAME) VALUES
('课程_1'), ('课程_2'), ('课程_3'), ('课程_4');
INSERT INTO sc VALUES
(1, 1), (1, 2), (1, 3), (1, 4),
(2, 1), (2, 2), (2, 3),
(3, 1), (3, 2),
(4, 1);
三、操作
查询学生ddd未选的课程:使用左外连接,并查询为空的
SELECT course.name
-- select *
FROM
course LEFT JOIN
(
SELECT *
FROM sc
WHERE sc.student_id =
(
SELECT id
FROM student
WHERE NAME = 'ddd'
-- limit 0,1
)
) AS sc_1
ON course.id = sc_1.course_id
WHERE sc_1.student_id IS NULL;
补:课本案例,实现左外、右外:
1.创建表结构:
CREATE TABLE R(
A CHAR(2),
B CHAR(2),
C CHAR(2)
);
CREATE TABLE S(
B CHAR(2),
E CHAR(2)
);
2.插入值:
INSERT INTO R VALUES
('a1', 'b1', '5'),
('a1', 'b2', '6'),
('a2', 'b3', '8'),
('a2', 'b4', '12');
INSERT INTO S VALUES
('b1', '3'),
('b2', '7'),
('b3', '10'),
('b3', '2'),
('b5', '2');
3.测试左外:
SELECT *
FROM r
LEFT JOIN s ON r.b = s.b;
4.测试右外:
SELECT *
FROM r
RIGHT JOIN s ON r.b = s.b;