准备工作,新建名为students的数据,三张表分别是student,courses,stu_cou,并创建外键约束,级联删除更新,插入数据。
/*创建数据库*/ create database if not EXISTS students character set utf8 collate utf8_general_ci; /*创建表*/ use students; create table if not EXISTS student ( stuID int(5) not null primary key, stuName varchar(50) not null, stuSex CHAR(10), stuAge smallint ); CREATE TABLE if not EXISTS courses( couID int not null primary key auto_increment COMMENT '学号', couName varchar(50) not null DEFAULT('大学英语'), couHours smallint UNSIGNED COMMENT '学时', couCredit float DEFAULT(2) COMMENT '学分' )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_0900_ai_ci; CREATE TABLE if not EXISTS stu_cou( ID int not null primary key auto_increment, stuID int(5) not null COMMENT '学号', couID int not null COMMENT '课程编号', time timestamp not null DEFAULT(now()) ); /*添加外键约束*/ alter table stu_cou add CONSTRAINT fk_stuid foreign key(stuID) REFERENCES student(stuID) ON UPDATE CASCADE ON DELETE CASCADE ; alter table stu_cou add CONSTRAINT fk_couid foreign key(couID) REFERENCES courses(couID) ON UPDATE CASCADE ON DELETE CASCADE ; /*插入数据*/ insert into student(stuID,stuName,stuSex,stuAge) values(1001,'张三','男',19),(1002,'李四','男',18),(1003,'王五','男',18),(1004,'黄丽丽','女',18),(1005,'李晓辉','女',19),(1006,'张敏','女',18); insert into student VALUES(1007,'五条人','男',20),(1008,'胡五伍','女',19); insert into courses(couID,couName,couHours,couCredit) values(50,'大学英语',64,2),(60,'计算机基础',78,2.5),(70,'Java程序设计',108,6),(80,'数据库应用',48,2.5); insert into stu_cou(stuID,couID) values(1001,50),(1001,60),(1001,70),(1001,80),(1002,50),(1002,60),(1002,70),(1002,80),(1003,50),(1003,60),(1003,70),(1003,80),(1004,50),(1004,60),(1004,70),(1004,80),(1005,50),(1005,60),(1005,70),(1005,80),(1006,50),(1006,60),(1006,70),(1006,80); alter table stu_cou add COLUMN grade FLOAT null; UPDATE stu_cou set grade=(SELECT FLOOR(50 +RAND() * 50)); alter table student add COLUMN stuColleage varchar(100) null; update student set stuColleage='大数据学院' where stuID BETWEEN 1001 and 1003; update student set stuColleage='物流学院' where stuID BETWEEN 1004 and 1006; update student set stuColleage='康养学院' where stuID BETWEEN 1007 and 1008;View Code
1.内连接
语法:select 字段列表 from 表1 [as 别名1],表2 [as 别名2]....where 表1.字段 = 表2.字段 AND 其它查询条件
(1)查询student表和courses表的内容。
SELECT * from student,courses;
此处的结果是student表的8行记录*courses表的4行记录,总共有32行记录(笛卡尔积),也叫作全连接,形成的结果大多数没有意义。
为表指定别名有两种方式:
第一种是通过关键字AS指定
SELECT * from student as s,courses as c;
第二种是在表名后直接加表的别名实现(注意有空格)
SELECT * from student s,courses c;
参考文章:
https://zhuanlan.zhihu.com/p/393923248 MySQL多表查询史上最强讲解
标签:多表,50,查询,courses,student,MySQL,80,null,stuID From: https://www.cnblogs.com/YorkZhangYang/p/16849255.html