Mysql practice questions 13.1
Follow the public account Reply: ``11.15'' View full content
Create a student table (student number, name, gender, age, major), and insert some data
Create a course table (course number, course name), insert department data
Create an elective form (student number, course number, grades), and insert part of the data. Complete the following query:
First create a database to establish three tables
mysql> create table students(
-> id int(3),
-> name varchar(20),
-> sex varchar(10),
-> age int(3),
-> major varchar(30)
-> );
mysql> create table kecheng(
-> kcid int(3),
-> kcname varchar(30)
-> );
mysql> create table xianxiu(
-> id int(3),
-> kcid int(3),
-> result int(3)
-> );
adding data
insert into students(id,name,sex,age,major)
-> values(1,'张三','男',18,'经济'),
-> (2,'张四','男',19,'金融'),
-> (3,'张五','男',18,'法学'),
-> (4,'张六','女',18,'数学'),
-> (5,'李四','女',18,'数学'),
-> (6,'李五','女',20,'金融'),
-> (7,'王五','男',18,'地理');
insert into kecheng(kcid,kcname)
-> values(1,'食品加工'),
-> (2,'机械加工'),
-> (3,'计算机组装'),
-> (4,'哲学'),
-> (5,'刑法学');
insert into xianxiu(id,kcid,result)
-> values(1,2,99),
-> (2,2,98),
-> (3,1,97),
-> (4,3,99),
-> (5,4,99),
-> (6,null,null),
-> (7,null,null);
1. Query the information of the selected students and their selected courses
select students.*,kecheng.* from students join kecheng join xianxiu on kecheng.kcid=xianxiu.kcid and students.id=xianxiu.id;
2. Query the information of students who have selected courses and their selected courses and students who have not selected courses
>select students.*,kecheng.* from students left join xianxiu on students.id=xianxiu.id left join kecheng on xianxiu.kcid=kecheng.kcid
3. Information about students who choose courses and their selected courses and courses not selected by students
>select students.*,kecheng.* from students right join xianxiu on students.id=xianxiu.id right join kecheng on xianxiu.kcid=kecheng.kcid;
4. Query all the information in steps 2 and 3
>select students.*,kecheng.* from students left join xianxiu on students.id=xianxiu.id left join kecheng on xianxiu.kcid=kecheng.kcid
>union
>select students.*,kecheng.* from students right join xianxiu on students.id=xianxiu.id right join kecheng on xianxiu.kcid=kecheng.kcid;
5. Query the course information of the course number 1 and the student ID of the student who chose the course
elect kecheng.kcid,kecheng.kcname,students.id from students join kecheng join xianxiu on kecheng.kcid=xianxiu.kcid and students.id=xianxiu.id where xianxiu.kcid=1;