Mysql 实例:mysql语句练习50题(sqlalchmy写法)
为了练习sql语句,在网上找了一些题,自己做了一遍,收益颇多.很多地方换一种思路,有更好的写法,欢迎指正.
题目地址:https://blog.csdn.net/fashion2014/article/details/78826299 ,他有更好的写法
参考视频 https://www.bilibili.com/video/BV1q4411G7Lw?p=1
表名和字段
–1.学生表
Student(id,name,birth,sex) –学生编号,学生姓名, 出生年月,学生性别
–2.课程表
Course(id,name) – –课程编号, 课程名称
–3.教师表
Teacher(id,name,cou_id) –教师编号,教师姓名,课程id
–4.成绩表
Score(id,score,stu_id,cou_id) –成绩编号,分数,学生编号,课程编号
建表
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,Integer,String,ForeignKey,DateTime from sqlalchemy.orm import relationship,sessionmaker engine = create_engine( "mysql+pymysql://root:123456@localhost:3306/school?charset=utf8", max_overflow=20, pool_size=5, pool_timeout=30, pool_recycle=20 ) Base = declarative_base() #class Stu2Course(Base): # __tablename__ = "student_course" # id = Column(Integer,primary_key=True,autoincrement=True) # stu_id = Column(Integer,ForeignKey("student.id")) # course_id = Column(Integer,ForeignKey("course.id")) #class Stu2Teacher(Base): # __tablename__ = "student_teacher" # id = Column(Integer,primary_key=True,autoincrement=True) # stu_id = Column(Integer,ForeignKey("student.id")) # tea_id = Column(Integer,ForeignKey("teacher.id")) class Stu(Base): __tablename__ = "student" id = Column(Integer,primary_key=True) name = Column(String(32),nullable=False) birth = Column(String(32),nullable=False) sex = Column(String(5),nullable=False) grades = relationship("Grade",backref="student") #courses = relationship("Course",secondary="Stu2Course",backref="student") # teachers = relationship("Teacher",secondary="Stu2Teacher",backref="student") class Course(Base): __tablename__ = "course" id = Column(Integer,primary_key=True) name = Column(String(32),nullable=False) grades = relationship("Grade",backref="course") teachers = relationship("Teacher",backref="teacher") class Teacher(Base): __tablename__ = "teacher" id = Column(Integer,primary_key=True) name = Column(String(32),nullable=False) cou_id = Column(Integer,ForeignKey("course.id")) class Grade(Base): __tablename__ = "grade" id = Column(Integer,primary_key=True) score = Column(Integer,nullable=False) stu_id = Column(Integer,ForeignKey("student.id")) cou_id = Column(Integer,ForeignKey("course.id")) Session = sessionmaker(bind=engine) session = Session() if __name__ == "__main__": Base.metadata.create_all(engine) #Base.metadata.drop_all(engine)
插入数据
#学生表 insert into student values('01' , '赵雷' , '1990-01-01' , '男'); insert into student values('02' , '钱电' , '1990-12-21' , '男'); insert into student values('03' , '孙风' , '1990-05-20' , '男'); insert into student values('04' , '李云' , '1990-08-06' , '男'); insert into student values('05' , '周梅' , '1991-12-01' , '女'); insert into student values('06' , '吴兰' , '1992-03-01' , '女'); insert into student values('07' , '郑竹' , '1989-07-01' , '女'); insert into student values('08' , '王菊' , '1990-01-20' , '女'); #课程表 insert into course values('01' , '语文'); insert into course values('02' , '数学'); insert into course values('03' , '英语'); #教师表 insert into teacher values('01' , '张三','01'); insert into teacher values('02' , '李四','02'); insert into teacher values('03' , '王五','03'); #成绩表 insert into grade values(1,80,'01' , '01'); insert into grade values(2,90,'01' , '02'); insert into grade values(3,99,'01' , '03'); insert into grade values(4,70,'02' , '01'); insert into grade values(5,60,'02' , '02'); insert into grade values(6,80,'02' , '03'); insert into grade values(7,80,'03' , '01'); insert into grade values(8,80,'03' , '02'); insert into grade values(9,80,'03' , '03'); insert into grade values(10,50,'04' , '01'); insert into grade values(11,30,'04' , '02'); insert into grade values(12,20,'04' , '03'); insert into grade values(13,76,'05' , '01'); insert into grade values(14,87,'05' , '02'); insert into grade values(15,31,'06' , '01'); insert into grade values(16,34,'06' , '03'); insert into grade values(17,89,'07' , '02'); insert into grade values(18,98,'07' , '03');
练习题和sql语句
#1 查询01课程比02课程成绩高的学生的信息以及课程分数 # 找出课程为01的学生的学生信息以及成绩 # 找出课程为02的学生的学生信息以及成绩 data_1 = session.query(Grade.stu_id,Grade.cou_id,Grade.score).filter(Grade.cou_id==1).subquery() data_2 = session.query(Grade.stu_id,Grade.cou_id,Grade.score).filter(Grade.cou_id==2).subquery() data_3 = session.query(data_1.c.stu_id).filter(data_1.c.stu_id==data_2.c.stu_id,data_1.c.score>data_2.c.score).subquery() #学生信息 data_4 = session.query(Stu).filter(Stu.id == data_3.c.stu_id).all() #课程分数 data_5 = session.query(Stu.name,data_1.c.stu_id,data_1.c.score,data_2.c.score).filter( data_1.c.stu_id==data_2.c.stu_id, data_1.c.score>data_2.c.score, Course.id==data_1.c.cou_id, Stu.id == data_1.c.stu_id, ).all() print([v for v in data_5])
#2 查询平均值大于等于60分的同学的学生编号和学生成绩
from sqlalchemy.sql import func
#data = session.query(Stu.id,Stu.name,func.avg(Grade.score)).join(
# Stu
# ).filter(
# Stu.id ==Grade.stu_id
# ).group_by(Grade.stu_id).having(func.avg(Grade.score)>=60).all()
#print([v for v in data])
#3、查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩
#data = session.query(Stu.id,Stu.name,func.count(Grade.stu_id),func.sum(Grade.score)).join(
# Stu
# ).filter(
# Stu.id ==Grade.stu_id
# ).group_by(Grade.stu_id).all()
#print([v for v in data])
#4、查询"李"姓老师的数量
#data = session.query(Teacher.id,Teacher.name,).filter(Teacher.name.like("李%")).all()
#print([v for v in data])
#5、查询学过"张三"老师授课的同学的信息
#data_1 = session.query(Teacher.cou_id).filter(Teacher.name=="张三").subquery()
#data = session.query(Stu.id).filter(Stu.id==Grade.stu_id,Grade.cou_id==data_1.c.cou_id).all()
#print([v for v in data])
#6、查询没学过"张三"老师授课的同学的信息
from sqlalchemy import not_,and_
#data_1 = session.query(Teacher.cou_id).filter(Teacher.name=="张三").subquery()
#data_2 = session.query(Stu.id).filter(Stu.id==Grade.stu_id,Grade.cou_id==data_1.c.cou_id).all()
#data = session.query(Stu.id).filter(Stu.id.notin_([v[0] for v in data_2])).all()
#print([v[0] for v in data])
#7、查询学过编号为"01"并且也学过编号为"02"的课程的同学的信息
#data_1 = session.query(Stu.id).join(Grade).filter(Stu.id==Grade.stu_id,Grade.cou_id==1).subquery()
#data_2 = session.query(Stu.id).join(Grade).filter(Stu.id==Grade.stu_id,Grade.cou_id==2).subquery()
#data = session.query(Stu.id).filter(Stu.id==data_1.c.id,Stu.id==data_2.c.id).all()
#print([v for v in data])
#8、查询学过编号为"01"但是没有学过编号为"02"的课程的同学的信息
#data_1 = session.query(Stu.id).join(Grade).filter(Stu.id==Grade.stu_id,Grade.cou_id==1).all()
#data_2 = session.query(Stu.id).join(Grade).filter(Stu.id==Grade.stu_id,Grade.cou_id==2).all()
#data = session.query(Stu.id).filter(and_(Stu.id.in_([v[0] for v in data_1]),Stu.id.notin_([v[0] for v in data_2]))).all()
#print([v for v in data])
#9、查询没有学全所有课程的同学的信息
#data = session.query(Grade.stu_id).group_by(Grade.stu_id).having(func.count(Grade.cou_id)<3).all()
#print([v for v in data])
#10、查询至少有一门课与学号为"01"的同学所学相同的同学的信息
#data_1 = session.query(Grade.cou_id).filter(Grade.stu_id==1).subquery()
#data = session.query(Stu.id,Stu.name).join(Grade).filter(Grade.stu_id==Stu.id,Grade.cou_id==data_1.c.cou_id).group_by(Stu.id).all()
#print([v for v in data])
#11、查询和"01"号的同学学习的课程完全相同的其他同学的信息
#data_1 = session.query(Grade.cou_id).filter(Grade.stu_id==1).all()
#stu_ids = session.query(Stu.id).all()
#for stu_id in stu_ids:
# if stu_id[0] == 1:
# continue
# data_temp = session.query(Grade.cou_id).filter(Grade.stu_id==stu_id[0]).all()
# if data_1 == data_temp:
# data = session.query(Stu.id,Stu.name).filter(Stu.id==stu_id[0]).all()
# print([v for v in data])
#12、查询没学过"张三"老师讲授的任一门课程的学生姓名
#data_1 = session.query(Teacher.cou_id).filter(Teacher.name=="张三").subquery()
#data_2 = session.query(Grade.stu_id).filter(Grade.cou_id == data_1.c.cou_id).group_by(Grade.stu_id).all()
#data = session.query(Stu.id,Stu.name).filter(Stu.id.notin_([v[0] for v in data_2])).all()
#print([v for v in data])
#13、查询两门及其以上不及格课程的同学的学号,姓名及其平均成绩
#data = session.query(Grade.stu_id).filter(Grade.score<60).group_by(Grade.stu_id).having(func.count(Grade.cou_id)>=2).all()
#print([v for v in data])
#14、检索"01"课程分数小于60,按分数降序排列的学生信息
#data = session.query(
# Grade.stu_id,
# func.max(
# case([(Grade.cou_id==1,Grade.score)],else_=0)
# ),
# func.max(
# case([(Grade.cou_id==2,Grade.score)],else_=0)
# ),
# func.max(
# case([(Grade.cou_id==3,Grade.score)],else_=0)
# ),
# func.avg(Grade.score)
# ).group_by(Grade.stu_id).order_by(func.avg(Grade.score).desc()).all()
#print([v for v in data])
#15、按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩
from sqlalchemy import case
#data = session.query(
# Grade.stu_id,
# func.max(
# case([
# (Grade.cou_id==1,Grade.score)
# ],
# else_=0
# )
# ),
# func.max(
# case([
# (Grade.cou_id==2,Grade.score)
# ],
# else_=0
# )
# ),
# func.max(
# case([
# (Grade.cou_id==3,Grade.score)
# ],
# else_=0
# )
# ),
# func.avg(Grade.score)
# ).group_by(Grade.stu_id).order_by(func.avg(Grade.score).desc()).all()
#print([v for v in data])
#16.查询各科成绩最高分、最低分和平均分:以如下形式显示:课程ID,课程name,最高分,最低分,平均分,及格率,中等率,优良率,优秀率
# 及格为>=60,中等为:70-80,优良为:80-90,优秀为:>=90
#data = session.query(
# Grade.cou_id,
# Course.name,
# func.max(Grade.score),
# func.min(Grade.score),
# func.sum(case([(Grade.score>=60,1)],else_=0))/func.count(Grade.stu_id),
# func.sum(case([(Grade.score.in_(range(70,80)),1)],else_=0))/func.count(Grade.stu_id),
# func.sum(case([(Grade.score.in_(range(80,89)),1)],else_=0))/func.count(Grade.stu_id),
# func.sum(case([((Grade.score>=90),1)],else_=0))/func.count(Grade.stu_id),
# ).join(
# Course
# ).filter(
# Grade.cou_id == Course.id
# ).group_by(Grade.cou_id).all()
#print([v for v in data])
# 17、按各科成绩进行排序,并显示排名(实现不完全)
# mysql没有rank函数
# 加@score是为了防止用union all 后打乱了顺序
#data = session.query(func.row_number().over(order_by=Grade.score), Grade.score).filter(Grade.cou_id==1).all()
#print([v for v in data])
# 18、查询学生的总成绩并进行排名
#data = session.query(Grade.stu_id,func.sum(Grade.score).label('total_score'),
# func.row_number().over(order_by=func.sum(Grade.score).label('total_score'))
# ).group_by(Grade.stu_id).order_by(func.sum(Grade.score)).all()
#print([v for v in data])
# 19、查询不同老师所教不同课程平均分从高到低显示
#data = session.query(Grade.cou_id,Course.name,func.avg(Grade.score)).join(
# Course
# ).filter(
# Course.id == Grade.cou_id
# ).group_by(Grade.cou_id).order_by(func.avg(Grade.score)).all()
#print([v for v in data])
#20、查询所有课程的成绩第2名到第3名的学生信息及该课程成绩
#data_1 = session.query(
# Stu.id.label('st_id'),
# Grade.cou_id,
# Course.name,
# Grade.score,
# func.row_number().over(order_by=Grade.score,partition_by=Grade.cou_id).label('m'),
# ).join(Stu,Course).filter(
# Grade.stu_id == Stu.id,
# Course.id == Grade.cou_id
# ).subquery()
#data = session.query(data_1.c.name,data_1.c.st_id,data_1.c.m).filter(data_1.c.m.in_([2,3]) ).all()
#print([v for v in data])
#23、统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[0-60]及所占百分比
#data = session.query(
# Grade.cou_id,
# Course.name,
# func.count(Grade.stu_id),
# func.sum(case([(Grade.score.in_(range(85,100)),1)],else_=0))/func.count(Grade.stu_id),
# func.sum(case([(Grade.score.in_(range(70,85)),1)],else_=0))/func.count(Grade.stu_id),
# func.sum(case([(Grade.score.in_(range(60,70)),1)],else_=0))/func.count(Grade.stu_id),
# func.sum(case([(Grade.score.in_(range(0,60)),1)],else_=0))/func.count(Grade.stu_id),
# ).join(
# Course
# ).filter(
# Course.id == Grade.cou_id
# ).group_by(Grade.cou_id).all()
#print([v for v in data])
# 24、查询学生平均成绩及其名次
#data = session.query(Grade.stu_id,func.avg(Grade.score),
# func.row_number().over(order_by=func.avg(Grade.score))
# ).group_by(Grade.stu_id).all()
#print([v for v in data])
# 25、查询各科成绩前三名的记录
#data_1 = session.query(
# Stu.id.label('st_id'),
# Grade.cou_id,
# Course.name,
# Grade.score,
# func.row_number().over(order_by=Grade.score,partition_by=Grade.cou_id).label('m'),
# ).join(Stu,Course).filter(
# Grade.stu_id == Stu.id,
# Course.id == Grade.cou_id
# ).subquery()
#data = session.query(data_1.c.name,data_1.c.st_id,data_1.c.m).filter(data_1.c.m.in_([1,2,3]) ).all()
#print([v for v in data])
#26、查询每门课程被选修的学生数
#data = session.query(Grade.cou_id,func.count(Grade.stu_id)).group_by(Grade.cou_id).all()
#print([v for v in data])
# 27、查询出只有两门课程的全部学生的学号和姓名
#data = session.query(Stu.name,Stu.id).join(
# Grade
# ).filter(
# Grade.stu_id == Stu.id
# ).group_by(Grade.stu_id).having(func.count(Grade.cou_id)==2).all()
#print([v for v in data])
#28、查询男生、女生人数
#data = session.query(func.count(Stu.id)).group_by(Stu.sex).all()
#print([v for v in data])
#29、查询名字中含有"风"字的学生信息
#data = session.query(Stu.id,Stu.name).filter(Stu.name.like("%风%")).all()
#print([v for v in data])
# 30、查询同名同性学生名单,并统计同名人数
#data = session.query(Stu.name,func.count(1)).group_by(Stu.name,Stu.sex).having(func.count(1)>1).all()
#print([v for v in data])
# 31、查询1990年出生的学生名单
#data = session.query(Stu.name).filter(Stu.birth.like("%1990%")).all()
#print([v for v in data])
#32、查询每门课程的平均成绩,结果按平均成绩降序排列,平均成绩相同时,按课程编号升序排列
from sqlalchemy import desc
#data = session.query(Grade.cou_id,Course.name,func.avg(Grade.score)).join(
# Course).filter(
# Grade.cou_id ==Course.id
# ).group_by(Grade.cou_id).order_by(
# desc(func.avg(Grade.score))).order_by(Grade.cou_id).all()
#print([v for v in data])
#33、查询平均成绩大于等于85的所有学生的学号、姓名和平均成绩
#data = session.query(Grade.stu_id,Stu.name,func.avg(Grade.score)).join(
# Stu
# ).filter(
# Stu.id == Grade.stu_id
# ).group_by(Grade.stu_id).having(
# func.avg( Grade.score)>=85
# ).all()
#print([v for v in data])
#34、查询课程名称为"数学",且分数低于60的学生姓名和分数
#data_1 = session.query(Course.name,Grade.score,Grade.stu_id).join(Grade).filter(
# Grade.cou_id ==Course.id,
# Course.name == "数学",
# ).subquery()
#data = session.query(data_1.c.name,data_1.c.score,data_1.c.stu_id,Stu.name).join(
# Stu
# ).filter(
# data_1.c.stu_id ==Stu.id,
# data_1.c.score < 60,
# ).all()
#print([v for v in data])
#35、查询所有学生的课程及分数情况:
#data = session.query(
# Grade.stu_id,
# func.max(
# case([
# (Grade.cou_id==1,Grade.score)
# ],
# else_=0
# )
# ),
# func.max(
# case([
# (Grade.cou_id==2,Grade.score)
# ],
# else_=0
# )
# ),
# func.max(
# case([
# (Grade.cou_id==3,Grade.score)
# ],
# else_=0
# )
# ),
# ).group_by(Grade.stu_id).all()
#print([v for v in data])
# 36、查询任何一门课程成绩在70分以上的姓名、课程名称和分数
#data_1 = session.query(Grade.stu_id,Grade.cou_id,Grade.score).filter(
# Grade.score > 70
# ).subquery()
# 方式 一
#data = session.query(Stu.name,Stu.id,Course.name,data_1.c.score).join(
# Course).filter(
# data_1.c.cou_id == Course.id,
# data_1.c.stu_id == Stu.id
# ).all()
#方式二
#data = session.query(
# Stu.name,
# Stu.id,
# func.max(case([(data_1.c.cou_id==1,data_1.c.score)],else_=0)),
# func.max(case([(data_1.c.cou_id==2,data_1.c.score)],else_=0)),
# func.max(case([(data_1.c.cou_id==3,data_1.c.score)],else_=0)),
# ).filter(data_1.c.stu_id==Stu.id).group_by(data_1.c.stu_id).all()
#print([v for v in data])
#37、查询所有学生的所有不及格的课程并按课程编号降序
#data = session.query(Grade.stu_id,Stu.name,Grade.cou_id,Course.name,Grade.score).join(
# Stu,Course).filter(
# Stu.id == Grade.stu_id,
# Grade.cou_id == Course.id,
# Grade.score < 60 ,
# ).order_by(desc(Grade.cou_id)).all()
#print([v for v in data])
#38、查询课程编号为01且课程成绩在80分以上的学生的学号和姓名
#data = session.query(Grade.stu_id,Stu.name,Grade.score).join(
# Stu
# ).filter(
# Grade.stu_id == Stu.id,
# Grade.score >= 80,
# Grade.cou_id == 1,
# ).all()
#print([v for v in data])
#39、求每门课程的学生人数
#data = session.query(Grade.cou_id,Course.name,func.count(Grade.stu_id)).join(Course).filter(
# Course.id == Grade.cou_id
# ).group_by(Grade.cou_id).all()
#print([v for v in data])
#40、查询选修"张三"老师所授课程的学生中,成绩最高的学生信息及其成绩
#data_1 = session.query(Teacher.cou_id).filter(Teacher.name == "张三").subquery()
#data_2 = session.query(Grade.stu_id,Grade.score,Grade.cou_id).filter(Grade.cou_id==data_1.c.cou_id).subquery()
#data_3 = session.query(
# Stu.id,
# Stu.name,
# data_2.c.score,
# Course.name.label('cou_name'),
# func.row_number().over(order_by=-data_2.c.score,partition_by=Course.name,).label('m'),
# ).join(
# Course
# ).filter(
# data_2.c.stu_id== Stu.id,
# Course.id == data_2.c.cou_id
# ).subquery()
#data = session.query(data_3.c.name,data_3.c.id,data_3.c.cou_name).filter(data_3.c.m.in_([1]) ).all()
#print([v for v in data])
#41、查询不同课程成绩相同的学生的学生编号、课程编号、学生成绩
#data_1 = session.query(Grade.stu_id,Grade.score).group_by(Grade.stu_id,Grade.score).subquery()
#data_2 = session.query(data_1.c.stu_id.label('m')).group_by(data_1.c.stu_id).having(func.count(data_1.c.stu_id)<2).subquery()
#data = session.query(Grade.score,Grade.stu_id).filter(Grade.stu_id==data_2.c.m).group_by(Grade.stu_id).having(func.count(Grade.cou_id)>1).all()
#print([v for v in data])
# 42、查询每门功成绩最好的前两名
#data_1 = session.query(
# Stu.id.label('st_id'),
# Grade.cou_id,
# Course.name,
# Grade.score,
# func.row_number().over(order_by=Grade.score,partition_by=Grade.cou_id).label('m'),
# ).join(Stu,Course).filter(
# Grade.stu_id == Stu.id,
# Course.id == Grade.cou_id
# ).subquery()
#data = session.query(data_1.c.name,data_1.c.st_id,data_1.c.m).filter(data_1.c.m.in_([1,2]) ).all()
#print([v for v in data])
#43、统计每门课程的学生选修人数(超过5人的课程才统计)。要求输出课程号和选修人数,查询结果按人数降序排列,
#data_1 = session.query(Grade.cou_id,func.count(Grade.stu_id).label('s_count')).group_by(Grade.cou_id).having(func.count(Grade.stu_id)>5).subquery()
#data = session.query(Course.id,Course.name,data_1.c.s_count).filter(Course.id==data_1.c.cou_id).order_by(desc(
#data_1.c.s_count
# )).order_by(Course.id).all()
#print([v for v in data])
#44、检索至少选修两门课程的学生学号
#data = session.query(Grade.stu_id).group_by(Grade.stu_id).having(func.count(Grade.cou_id)>=2).all()
#print([v for v in data])
#45、查询选修了全部课程的学生信息
#data = session.query(Grade.stu_id,Stu.name).join(Stu).filter(
# Grade.stu_id == Stu.id
# ).group_by(Grade.stu_id).having(func.count(Grade.cou_id)==3).all()
#print([v for v in data])
#46、查询各学生的年龄
#data = session.query(Stu.id,Stu.birth,func.datediff("2020-03-31",Stu.birth)/365).all()
#print([v for v in data])
#47、查询本周过生日的学生
# 放到同一年进行比较
import time,datetime
#day = datetime.date(2020,3,31).weekday() #0-6 表示星期一到星期天
#gap_day = 7-day
#print(gap_day)
#import re
#data = session.query(Stu.id,Stu.name
# ).filter(
# func.abs(func.datediff('2020-03-31',func.concat('2020-',func.substring(Stu.birth,6,5))))<gap_day
# ).all()
#print([v for v in data])
#48、查询下周过生日的学生
#data = session.query(Stu.id,Stu.name
# ).filter(
# func.abs(func.datediff('2020-03-31',func.concat('2020-',func.substring(Stu.birth,6,5))))<gap_day
# ).all()
#print([v for v in data])
#49、查询本月过生日的学生
#data = session.query(Stu.id,Stu.name
# ).filter(
# func.month(func.now())== func.month(Stu.birth)
# ).all()
#print([v for v in data])
#50、查询下月过生日的学生
data = session.query(Stu.id,Stu.name
).filter(
case([(func.month(func.now())==12,func.month(Stu.birth)==1)],else_=(func.month(func.now())==func.month(Stu.birth)+1))
).all()
print([v for v in data])
本文来自博客园,作者:秋华,转载请注明原文链接:https://www.cnblogs.com/qiu-hua/p/12493627.html