创建 teacher 表,并插入以下数据
create table `teacher` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(20) not null,
`phone_number` varchar(20) not null,
`email` varchar(64),
PRIMARY KEY (`id`)
);
insert into teacher (id, username, phone_number, email) values
(null, 'Imooc', '13552480001', 'imooc@imooc.com'),
(null, 'Lily', '13552480002', 'lily@imooc.com'),
(null, 'Tom', '13552480003', 'tom@imooc.com'),
(null, 'Mary', '13552480004', 'mary@imooc.com'),
(null, 'Yanyan', '13552480005', 'yanyan@imooc.com'),
(null, 'Andy', '13552480006', 'andy@imooc.com'),
(null, 'John', '13552480007', 'john@imooc.com');
teacher 表数据:
清空 course 表,然后修改表结构,并插入以下数据
delete from course;
alter table course change teacher teacher_id int(11);
INSERT INTO course (id, course_name,teacher_id, create_time) VALUES
(null, 'Python编程', 1, now()),
(null, 'MySQL数据库',2, now()),
(null, '爬虫开发', 3, now()),
(null, '数据分析', 4, now()),
(null, '人工智能', 5, now());
(null, 'Java开发', 99, now());
course 表数据:
LEFT JOIN 左连接查询
以左表为基准,若右表没有对应的值,用 NULL 来填补
select c.id as course_id, c.course_name, c.teacher_id, t.username as teacher_name from course c left join teacher t on c.teacher_id = t.id;
cid AS course_id
将 course 表中的 id 字段重命名为 course_idt.username as teacher_name
将 teacher 表中的 username 字段重命名为 teacher_name- on 后面是连接表的条件
course c
将 course 表简写为 cteacher t
将 teacher 表简写为 t