新健库 ,新增字段+类型+约束
设计表:外键(自增)
新建查询
建立表模型
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
/* 数据导入: Navicat Premium Data Transfer Source Server : localhost Source Server Type : MySQL Source Server Version : 50624 Source Host : localhost Source Database : sqlexam Target Server Type : MySQL Target Server Version : 50624 File Encoding : utf-8 Date: 10/21/2016 06:46:46 AM */ SET NAMES utf8; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for `class` -- ---------------------------- DROP TABLE IF EXISTS `class`; CREATE TABLE `class` ( `cid` int(11) NOT NULL AUTO_INCREMENT, `caption` varchar(32) NOT NULL, PRIMARY KEY (`cid`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of `class` -- ---------------------------- BEGIN; INSERT INTO `class` VALUES ('1', '三年二班'), ('2', '三年三班'), ('3', '一年二班'), ('4', '二年九班'); COMMIT; -- ---------------------------- -- Table structure for `course` -- ---------------------------- DROP TABLE IF EXISTS `course`; CREATE TABLE `course` ( `cid` int(11) NOT NULL AUTO_INCREMENT, `cname` varchar(32) NOT NULL, `teacher_id` int(11) NOT NULL, PRIMARY KEY (`cid`), KEY `fk_course_teacher` (`teacher_id`), CONSTRAINT `fk_course_teacher` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`tid`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of `course` -- ---------------------------- BEGIN; INSERT INTO `course` VALUES ('1', '生物', '1'), ('2', '物理', '2'), ('3', '体育', '3'), ('4', '美术', '2'); COMMIT; -- ---------------------------- -- Table structure for `score` -- ---------------------------- DROP TABLE IF EXISTS `score`; CREATE TABLE `score` ( `sid` int(11) NOT NULL AUTO_INCREMENT, `student_id` int(11) NOT NULL, `course_id` int(11) NOT NULL, `num` int(11) NOT NULL, PRIMARY KEY (`sid`), KEY `fk_score_student` (`student_id`), KEY `fk_score_course` (`course_id`), CONSTRAINT `fk_score_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`cid`), CONSTRAINT `fk_score_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`sid`) ) ENGINE=InnoDB AUTO_INCREMENT=53 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of `score` -- ---------------------------- BEGIN; INSERT INTO `score` VALUES ('1', '1', '1', '10'), ('2', '1', '2', '9'), ('5', '1', '4', '66'), ('6', '2', '1', '8'), ('8', '2', '3', '68'), ('9', '2', '4', '99'), ('10', '3', '1', '77'), ('11', '3', '2', '66'), ('12', '3', '3', '87'), ('13', '3', '4', '99'), ('14', '4', '1', '79'), ('15', '4', '2', '11'), ('16', '4', '3', '67'), ('17', '4', '4', '100'), ('18', '5', '1', '79'), ('19', '5', '2', '11'), ('20', '5', '3', '67'), ('21', '5', '4', '100'), ('22', '6', '1', '9'), ('23', '6', '2', '100'), ('24', '6', '3', '67'), ('25', '6', '4', '100'), ('26', '7', '1', '9'), ('27', '7', '2', '100'), ('28', '7', '3', '67'), ('29', '7', '4', '88'), ('30', '8', '1', '9'), ('31', '8', '2', '100'), ('32', '8', '3', '67'), ('33', '8', '4', '88'), ('34', '9', '1', '91'), ('35', '9', '2', '88'), ('36', '9', '3', '67'), ('37', '9', '4', '22'), ('38', '10', '1', '90'), ('39', '10', '2', '77'), ('40', '10', '3', '43'), ('41', '10', '4', '87'), ('42', '11', '1', '90'), ('43', '11', '2', '77'), ('44', '11', '3', '43'), ('45', '11', '4', '87'), ('46', '12', '1', '90'), ('47', '12', '2', '77'), ('48', '12', '3', '43'), ('49', '12', '4', '87'), ('52', '13', '3', '87'); COMMIT; -- ---------------------------- -- Table structure for `student` -- ---------------------------- DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `sid` int(11) NOT NULL AUTO_INCREMENT, `gender` char(1) NOT NULL, `class_id` int(11) NOT NULL, `sname` varchar(32) NOT NULL, PRIMARY KEY (`sid`), KEY `fk_class` (`class_id`), CONSTRAINT `fk_class` FOREIGN KEY (`class_id`) REFERENCES `class` (`cid`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of `student` -- ---------------------------- BEGIN; INSERT INTO `student` VALUES ('1', '男', '1', '理解'), ('2', '女', '1', '钢蛋'), ('3', '男', '1', '张三'), ('4', '男', '1', '张一'), ('5', '女', '1', '张二'), ('6', '男', '1', '张四'), ('7', '女', '2', '铁锤'), ('8', '男', '2', '李三'), ('9', '男', '2', '李一'), ('10', '女', '2', '李二'), ('11', '男', '2', '李四'), ('12', '女', '3', '如花'), ('13', '男', '3', '刘三'), ('14', '男', '3', '刘一'), ('15', '女', '3', '刘二'), ('16', '男', '3', '刘四'); COMMIT; -- ---------------------------- -- Table structure for `teacher` -- ---------------------------- DROP TABLE IF EXISTS `teacher`; CREATE TABLE `teacher` ( `tid` int(11) NOT NULL AUTO_INCREMENT, `tname` varchar(32) NOT NULL, PRIMARY KEY (`tid`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of `teacher` -- ---------------------------- BEGIN; INSERT INTO `teacher` VALUES ('1', '张磊老师'), ('2', '李平老师'), ('3', '刘海燕老师'), ('4', '朱云海老师'), ('5', '李杰老师'); COMMIT; SET FOREIGN_KEY_CHECKS = 1; 拷贝上述代码,新建一个.sql文件,保存到桌面(保存的格式utf8 注意编码) 打开navicat新建数据库day41,选中新建的数据库鼠标右键选择运行SQL文件 弹出文件框,选中刚刚保存到桌面的.sql文件即可 #1、查询所有的课程的名称以及对应的任课老师姓名 SELECT course.cname, teacher.tname FROM course INNER JOIN teacher ON course.teacher_id = teacher.tid; #4、查询平均成绩大于八十分的同学的姓名和平均成绩 SELECT student.sname, t1.avg_num FROM student INNER JOIN ( SELECT student_id, avg(num) AS avg_num FROM score GROUP BY student_id HAVING avg(num) > 80 ) AS t1 ON student.sid = t1.student_id; #7、 查询没有报李平老师课的学生姓名(找出报名李平老师课程的学生,然后取反就可以) SELECT student.sname FROM student WHERE sid NOT IN ( SELECT DISTINCT student_id FROM score WHERE course_id IN ( SELECT course.cid FROM course INNER JOIN teacher ON course.teacher_id = teacher.tid WHERE teacher.tname = '李平老师' ) ); #8、 查询没有同时选修物理课程和体育课程的学生姓名(没有同时选修指的是选修了一门的,思路是得到物理+体育课程的学生信息表,然后基于学生分组,统计count(课程)=1) SELECT student.sname FROM student WHERE sid IN ( SELECT student_id FROM score WHERE course_id IN ( SELECT cid FROM course WHERE cname = '物理' OR cname = '体育' ) GROUP BY student_id HAVING COUNT(course_id) = 1 ); # 9、 查询挂科超过两门(包括两门)的学生姓名和班级 select student.sname,class.caption from class INNER JOIN student on class.cid = student.class_id WHERE student.sid in (select student_id from score where num < 60 GROUP BY student_id HAVING COUNT(course_id) >=2) ;
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1、查询所有的课程的名称以及对应的任课老师姓名 SELECT course.cname,teacher.tname FROM course INNER JOIN teacher on teacher.tid=course.teacher_id; 2、查询学生表中男女生各有多少人 SELECT gender,COUNT(sid) FROM student GROUP BY gender; 3、查询物理成绩等于100的学生的姓名 SELECT student.sname FROM student WHERE student.sid in ( SELECT score.student_id FROM score WHERE num =100); 4、查询平均成绩大于八十分的同学的姓名和平均成绩 SELECT student.sname, t1.avg_num FROM student INNER JOIN ( SELECT score.student_id,AVG(num) as avg_num FROM score GROUP BY num HAVING AVG(num)>80) as t1 on t1.student_id=student.sid; 5、查询所有学生的学号,姓名,选课数,总成绩 学生列表:sid sname 成绩列表:num count(course_id) student_id SELECT student.sname,student.sid,t1.num,t1.total_num as '课程数' FROM studentINNER JOIN ( SELECT COUNT(score.student_id) as total_num,score.num,score.student_id FROM score GROUP BY score.student_id) as t1 ON t1.student_id=student.sid 6、 查询姓李老师的个数 count 统计不分组的个数 SELECT COUNT(tname) FROM teacher WHERE tname LIKE '%李%' 7、 查询没有报李平老师课的学生姓名 遇到多对对表先拿在里面的 最终结果在取反 SELECT student.sname FROM student WHERE student.sid not in ( #拿到学生姓名 SELECT DISTINCT score.student_id FROM score WHERE score.course_id in ( #3 拿到所有报名李平老师课程的学生id号 此处去重一下 一个学生可以报名多个课程 (必须先过滤报了课程的学生id 学生报课程是用一个id 报多门课程id 如果用not in 只要学生报了多门课程的 报的多门的课程id 所对应已经报了课程就被过滤掉了用的是一个id) 遇到多对对表先拿在里面 的 最终结果在取反 SELECT course.cid FROM course WHERE course.teacher_id in ( #2 拿到老师的课程id 2 4 SELECT teacher.tid FROM teacher WHERE teacher.tname='李平老师' ) #1 拿到老师的id ) ) 8、 查询物理课程比生物课程分数高的学生的学号 比较同一个学生 物理课程比生物课程分数高 不同学生比不出来结果 错误示范: SELECT t1.student_id FROM ( SELECT score.student_id,course.cid,score.num,score.sid FROM course INNER JOIN score on score.course_id=course. cid WHERE course.cname in ('物理') #物理的id号) as t1 INNER JOIN (SELECT score.student_id,course.cid,score.num,score.sid FROM course INNER JOIN score on score.course_id=course. cid WHERE course.cname in ('生物') #生物的id号 ) as t2 ON t1.sid=t2.sid WHERE t1.num > t2.num #比不出结果 正确示范; SELECT t1.student_id FROM ( SELECT score.student_id,score.num,score.sid FROM course INNER JOIN score on score.course_id=course.cid WHERE course.cname in ('物理') #物理的id号 ) as t1 INNER JOIN (SELECT score.student_id,score.num,score.sid FROM course INNER JOIN score on score.course_id=course.cid WHERE course.cname in ('生物') #生物的id号) as t2 ON t1.student_id=t2.student_id WHERE t1.num > t2.num 9、 查询没有同时选修物理课程和体育课程的学生姓名 先拿到课程id号 去查询 学生的student_id 学生有可能两个都报了 我们只要报一个的 按学生分组 统计学生课程次数为1的 SELECT score.student_id FROM score WHERE score.course_id IN ( SELECT course.cid FROM course WHERE course.cname in ('体育','物理')) #2 3 GROUP BY score.student_id HAVING COUNT(score.course_id)=1 ; 10、查询挂科超过两门(包括两门)的学生姓名和班级 1 拿到学生id 从score表 过滤条件 num<60 分组 学生id 在过滤分组下面课程>=2 SELECT class.caption,student.sname FROM student INNER JOIN class on class.cid=student.class_id WHERE student.sid in ( SELECT score.student_id FROM score WHERE score.num <60 GROUP BY score.student_id HAVING COUNT(score.course_id) >=2); 11、查询选修了所有课程的学生姓名 统计课程总数 score表分组按学生student_id count(student_id)=课程总数 ① SELECT student.sname FROM student WHERE student.sid IN ( SELECT t1.student_id FROM ( SELECT score.student_id,COUNT(score.student_id) as num ,score.course_id,score.sid FROM score GROUP BY score.student_id) as t1 #按照学生去分组 拿到选修课程的个数 和学生的id 课程id INNER JOIN (SELECT course.cid,COUNT(course.cid)as ber FROM course )as t2 on t2.cid=t1.course_id WHERE t1.num = t2.ber ); ②简易版 select student.sname from student where sid in ( #统计组下面的课程数 select student_id from score group by student_id having count(course_id)=(select count(cid) from course)); 12、查询李平老师教的课程的所有成绩记录 SELECT score.num FROM score WHERE score.course_id IN ( SELECT course.cid FROM course WHERE course.teacher_id in ( SELECT teacher.tid FROM teacher WHERE teacher.tname='李平老师')); SELECT num FROM score WHERE course_id in (SELECT course.cid FROM course INNER JOIN teacher on teacher.tid =course.teacher_id WHERE teacher.tname='李平老师'); 13、查询全部学生都选修了的课程号和课程名 查询全部学生都选了的课程 和这个课程的cid score 分组课程 统计学生等于总学生数 SELECT cid,cname FROM course WHERE cid IN ( SELECT course_id FROM score GROUP BY course_id HAVING COUNT(student_id)=( SELECT COUNT(sid) FROM student)); 14、查询每门课程被选修的次数 SELECT COUNT(student_id),course_id FROM score GROUP BY course_id ; 15、查询之选修了一门课程的学生姓名和学号 SELECT sid ,sname FROM student INNER JOIN ( SELECT student_id FROM score GROUP BY student_id HAVING COUNT(course_id)=1) as t1 on t1.student_id = student.sid; 16、查询所有学生考出的成绩并按从高到低排序(成绩去重) #所有成绩 SELECT DISTINCT num FROM score I ORDER BY num desc; 17、查询平均成绩大于85的学生姓名和平均成绩 SELECT avg(num),sname FROM student INNER JOIN score on student.sid=score.student_id GROUP BY student_id HAVING AVG(num )>85; 18、查询生物成绩不及格的学生姓名和对应生物分数 SELECT sname,num FROM student INNER JOIN ( SELECT student_id,num FROM score WHERE course_id in ( SELECT cid FROM course WHERE cname='生物') and num < 60) as t1 on t1.student_id = student.sid ; 19、查询在所有选修了李平老师课程的学生中,这些课程(李平老师的课程,不是所有课程)平均成绩最高的学生姓名 SELECT sname FROM student WHERE student.sid in ( SELECT DISTINCT student_id FROM score WHERE course_id in ( SELECT cid FROM course INNER JOIN (SELECT * FROM teacher ) as t1 on course.teacher_id= t1.tid WHERE t1.tname='李平老师') GROUP BY student_id ORDER BY avg(num) DESC ) LIMIT 1; 20、查询每门课程成绩最好的前两名学生姓名 -- SELECT * FROM student RIGHT JOIN ( -- SELECT GROUP_CONCAT(student_id)as best_id FROM score GROUP BY course_id ORDER BY num DESC -- ) as t1 on t1.best_id = student.sid ; 只拿到了四个课程下面按照分数排名的学生id 21、查询不同课程但成绩相同的学号,课程号,成绩 22、查询没学过“叶平”老师课程的学生姓名以及选修的课程名称; 23、查询所有选修了学号为1的同学选修过的一门或者多门课程的同学学号和姓名; 24、任课最多的老师中学生单科成绩最高的学生姓名
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
create table book( id int primary key auto_increment, name varchar(16), price int ); create table author( id int primary key auto_increment, name varchar(16) ); create table book_author( id int primary key auto_increment, book_id int, author_id int );
-- 1查看每本书的作者
#书是一本 多个作者 拿唯一的书的id 通过分组按照书id分组 可以拿到书的唯一id group_concat(作者名) 拿到所有的作者 SELECT book.`name` , t.all_name FROM book INNER JOIN ( SELECT book_author.book_id, GROUP_CONCAT( author.`name` ) AS all_name FROM author INNER JOIN book_author ON author.id = book_author.author_id GROUP BY book_id ) as t #注 inner join 跟上你拼好的表 再去起别名!!!! on t.book_id=book.id;
-- 2 查看每位作者都有哪些作品
SELECT
author.`name`,
t1.all_name
FROM
author
INNER JOIN
(
SELECT GROUP_CONCAT(book.`name`) as all_name, book_author.author_id FROM book INNER JOIN book_author ON book.id = book_author.author_id GROUP BY
book.`name`
) AS t1 #注 inner join 跟上你拼好的表 再去起别名!!!!
ON t1.author_id= author.id
;
1查看所有可课程心得名称以及对应的任课老师的姓名
SELECT
course.cname ,
teacher.tname
FROM
course
INNER JOIN
teacher
on teacher.tid=course.teacher_id
2、查询学生表中男女生各有多少人
SELECT * FROM student;
SELECT gender,COUNT(gender) FROM student GROUP BY gender;
pymysql 模块
# import pymysql # #连接 # conn = pymysql.connect( # host = 'localhost', # port = 3306, # user = 'root', # password = '', # database = 'day41', # charset = 'utf8' # ) # 游标 # cursor =conn.cursor() #执行完毕后返回的结果默认的以元组显示 # cursor =conn.cursor(pymysql.cursors.DictCursor) #将查询结果做成字典的格式 # pymysql操作数据库 # 执行sql 语句 # 语句在mysql里面执行 # res=cursor.execute("select * from class") #执行sql语句 返回sql查询成功的记录数目 # print(res) #查询到的数据总条数 # print(cursor.fetchone()) # {'cid': 1, 'caption': '三年二班'} 获取一条查询结果 # 类似于管道取一条少一条 # print(cursor.fetchone()) #{'cid': 2, 'caption': '三年三班'} 获取一条查询结果 # # # print(cursor.fetchone()) #{'cid': 3, 'caption': '一年二班'} 获取一条查询结果 # cursor.scroll(1,'relative') #相对移动,第三条数据被截取 # # print(cursor.fetchall()) #[{'cid': 4, 'caption': '二年九班'}] # cursor.scroll(1,'absolute') #绝对移动,参照开始位置 # print(cursor.fetchall()) #[{'cid': 2, 'caption': '三年三班'}, {'cid': 3, 'caption': '一年二班'}, {'cid': 4, 'caption': '二年九班'}]
sql 注入问题不要手动去拼接查询的sql语句
username = input(">>>:").strip() password = input(">>>:").strip() sql = "select * from user where username='%s' and password='%s'"%(username,password) # 用户名正确 username >>>: jason' -- jjsakfjjdkjjkjs # 用户名密码都不对的情况 username >>>: xxx' or 1=1 --asdjkdklqwjdjkjasdljad #在sql里面 --代表注释掉 约束条件来判断的时候 1=1 is Ture password >>>: ''
正确注入
username = input(">>>:").strip()
password = input(">>>:").strip()
sql = "select * from user where username=%s and password=%s"
res=cursor.execute(sql,(username,password)) #sql会自己去拼接
增 改查
import pymysql conn = pymysql.connect(host='localhost', port=3306, user='root', password='', database='day41', #哪个库下面 charset='utf8', autocommit=True # 插入数据之后 确保无误后才会真正修改到数据库 在这里声明的话每次操作都会直接修改到数据库 ) cursor = conn.cursor(pymysql.cursors.DictCursor) username = input('》》》:') password = input('》》》: ') #插入数据 # sql = "insert into userinfo(name,password) values (%s,%s)" # 必须让mysql自己拼接 不然有可能自己拼接的在mysql里面执行的时候约束条件 # 有一个判断就直接进去了数据就不安全了 # res = cursor.execute(sql,(username,password)) # conn.commit() #确保数据无误后,commit之后才会将数据真正修改到数据库 # if res: # print(cursor.fetchall()) # pass # else: # print('用户名或密码错误!') #查询验证 # sql='select * from userinfo where name =%s and password=%s ' # res=cursor.execute(sql,(username,password)) # conn.commit() # if res: # pass # else: # print('密码或用户名错误') #更新数据 # sql = "update userinfo set name=%s where id =%s" # # res=cursor.execute(sql,(username,password)) # if res: # pass # else: # print('error')