美文网首页
Django ORM查询练习题45题(初级)

Django ORM查询练习题45题(初级)

作者: 孙子衡 | 来源:发表于2021-02-08 09:14 被阅读0次

    Django(2.x之后的版本)的项目创建 在这里不做赘述下面是app 目录

    image.png

    1, school app里的创表语句

    model.py
    from django.db import models
    
    # Create your models here.
    
    class Classes(models.Model):
       cid = models.IntegerField(primary_key=True)
       name = models.CharField(max_length=32,verbose_name='班级名称')
    
    class Student(models.Model):
       sno = models.IntegerField(primary_key=True)
       name = models.CharField(max_length=32,verbose_name='学生姓名')
       sex = models.SmallIntegerField(choices=((0, "女"), (1, "男")), verbose_name="性别", default=1)
       birthday = models.DateField()
       classes = models.ManyToManyField(Classes)
    
    class Theacher(models.Model):
       prof_choice = (
           (0,"教授"),
           (1,"副教授"),
           (2,"讲师"),
           (3,"助教"),
           (4,"后勤")
       )
       depart_choice = (
           (0,'计算机系'),
           (1,'电子工程系'),
           (2,"土木工程系"),
           (3,"农林工程系"),
           (4,"畜牧工程系"),
           (5,"财经商务系"),
           (6,"电子商务系"),
           (7,"心理学系")
       )
       tno = models.IntegerField(primary_key=True)
       name = models.CharField(max_length=32,verbose_name='姓名')
       sex = models.SmallIntegerField(choices=((0, "女"), (1, "男")), verbose_name="性别", default=1)
       birthday = models.DateField()
       prof = models.SmallIntegerField(choices=prof_choice,default=1,verbose_name='职称')
       depart = models.SmallIntegerField(choices=depart_choice,default=1,verbose_name='部门')
       course = models.ForeignKey("Course",null=True,blank=True,on_delete=models.CASCADE,related_name='tcourse')
    
    class Course(models.Model):
       cnno = models.CharField(max_length=32,verbose_name='课程编号')
       name = models.CharField(max_length=32,verbose_name='课程名字')
    class Score(models.Model):
       sno = models.ForeignKey(Student,related_name='student',on_delete=models.CASCADE)
       cno = models.ForeignKey(Course,related_name='scourse',on_delete=models.CASCADE)
       degree = models.IntegerField(verbose_name='分数')
    

    2. admin的注册语句(如何创建admin后台用户自己查询)

    admin.py
    from django.contrib import admin
    from school import models
    # Register your models here.
    
    @admin.register(models.Classes)
    class ClassAdmin(admin.ModelAdmin):
        list_display = ('cid','name')
    
    @admin.register(models.Course)
    class CourseAdmin(admin.ModelAdmin):
        list_display = ('cno','name')
    
    @admin.register(models.Student)
    class StudentAdmin(admin.ModelAdmin):
        list_display = ('sno','name','sex','birthday')
    
    @admin.register(models.Theacher)
    class TheacherAdmin(admin.ModelAdmin):
        list_display = ('tno','name','sex','birthday','prof','depart','course')
    
    @admin.register(models.Score)
    class ScoreAdmin(admin.ModelAdmin):
        list_display = ('sno','cno','degree')
    
    

    admin后台展示:

    image.png

    表数据在最下面 ⏬


    路由视图展示:

    image.png

    子路由代码

    urls.py
    from django.conf.urls import url
    from django.urls import path
    from school.views import sql_check
    
    urlpatterns = [
        path('check',sql_check),
    ]
    
    
    

    视图代码 下面的所有查询都在一个视图函数里

    import json
    from django.db.models import Q,Sum,Max,Min,Avg,Count
    from django.shortcuts import render,HttpResponse
    from django.http import HttpResponse
    from school.models import Classes,Student,Theacher,Course,Score
    # Create your views here.
    
    def sql_check(request):
      ''' 
    下面的所查询 都在这个函数里完成
    '''
        return HttpResponse('')
       
    

    1. 查询Student表中的所有记录的name , sex 和 class列

    def sql_check(request):
        stus = Student.objects.filter().values('name','sex','classes__cid')
        stu_data = [
            {"name":stu["name"],
            "sex":stu["sex"],
            "classes__cid":stu["classes__cid"]}
            for stu in stus
        ]
        return HttpResponse(json.dumps(stu_data), content_type='application/json')
     结果展示===>
    [
        {
            "name": "李军",
            "sex": 1,
            "classes__cid": 95033
        },
        {
            "name": "陆军",
            "sex": 1,
            "classes__cid": 95031
        },
        {
            "name": "匡明",
            "sex": 1,
            "classes__cid": 95031
        },
        {
            "name": "王丽",
            "sex": 0,
            "classes__cid": 95033
        },
        {
            "name": "曾华",
            "sex": 1,
            "classes__cid": 95033
        },
        {
            "name": "王芳",
            "sex": 0,
            "classes__cid": 95031
        }
    ]   
    

    2. 查询教师所有的单位即不重复的Depart列

    def sql_check(request):
        
        departs = Theacher.objects.filter().values('depart').distinct()
        depart = [depart['depart'] for depart in departs]
    
        return HttpResponse(json.dumps(depart), content_type='application/json')
    最终结果显示:
    [
        0,
        1
    ]
    

    3.查询Student表的所有记录

    def sql_check(request):
    
        stu = Student.objects.all()
        
        return HttpResponse('ok')
    

    4. 查询Score表中成绩在60到80之间的所有记录

    def sql_check(request):
    
        score = Score.objects.filter(Q(degree__gte=60)& Q(degree__lte=80))
        print(score)
        return HttpResponse('ok')
    
    
    

    5.查询Score表中成绩为85 86 或88 的记录

    def sql_check(request):
    
        score = Score.objects.filter(degree__in=[85,86,88])
        print(score)
        return HttpResponse('ok')
    

    6. 查询Student表中'95031'班或性别为 '女'的同学记录

    def sql_check(request):
    
    
        stu = Student.objects.filter(Q(classes__cid='95031') | Q(sex=0))
        print(stu)
        return HttpResponse('ok')
    

    7. 以Class降序查询Student表的所有记录

    def sql_check(request):
    
        stu = Student.objects.filter().order_by('-classes__cid')
        for s in stu:
            print(s.classes.all())
        return HttpResponse('ok')
    

    8. 以Cno升序 Degree降序查询Score表的所有记录

    def sql_check(request):
    
        scores = Score.objects.filter().order_by('cno','-degree')
        for score in scores:
            print(score.cno,score.degree)
        return HttpResponse('ok')
    

    9. 查询'95031'班的学生人数

    def sql_check(request):
    
        stu = Student.objects.filter(classes__cid='95031').count()
        print(stu)
        return HttpResponse('ok')
    

    10. 查询Score表中的最高分的学生学号和课程号

    def sql_check(request):
        
        degree__max = Score.objects.aggregate(Max('degree'))['degree__max']
        score = Score.objects.filter(degree=degree__max).values('sno','cno')
        print(score)
    
        return HttpResponse('ok')
    
    --->解法二:
    score = Score.objects.filter().order_by('degree').values('sno','cno').first()
    
    

    11.查询每门课的平均成绩

    def sql_check(request):
        
        score = Score.objects.values('cno').annotate(Avg('degree'))
        print(score)
        return HttpResponse('ok')
    

    12.查询Score表中至少有5名学生选修是以3开头的课程的平均数

    def sql_check(request):
        
        # 1. 查询 5名以上选修课程的cno
        scores = Score.objects.values('cno').annotate(Count('cno'))
        cno = [score['cno'] for score in scores if score['cno__count'] >= 5]
        # 2.查询 5名以上并以3开头选修课程的cno
        cnos = Score.objects.filter(Q(cno__name__startswith='3') &Q(cno__in=cno)).values('cno').distinct()
        cno = [cno['cno'] for cno in cnos]
        #3. 计算平均分
        degree = Score.objects.filter(cno__in=cno).values('cno').annotate(Avg('degree'))
        print(degree)
        return HttpResponse('ok')
    打印结果显示:
    <QuerySet [{'cno': 105, 'degree__avg': 81.5}]>
    

    13.查询分数大于70,小于90的Sno列

    def sql_check(request):
    
        score = Score.objects.filter(Q(degree__gt=70) & Q(degree__lt=90)).values('sno').distinct()
        print(score)
        return HttpResponse('ok')
    打印结果显示:
    <QuerySet [{'sno': 103}, {'sno': 105}, {'sno': 109}]>
    

    14.查询所有学生的Sname, Cnno和Degree列

    def sql_check(request):
        score = Score.objects.filter().values('sno__name','cno__cnno','degree')
        print(score)
        return HttpResponse('ok')
    打印结果显示:
    <QuerySet [{'sno__name': '陆军', 'cno__cnno': '3-205', 'degree': 86}, {'sno__name': '匡明', 'cno__cnno': '3-205', 'degree': 75}, {'sno__name': '王芳', 'cno__cnno': '3-205', 'degree': 68}, {'sno__name': '陆军', 'cno__cnno': '3-105', 'degree': 92}, {'sno__name': '匡明', 'cno__cnno': '3-105', 'degree': 88}, {'sno__name': '王芳', 'cno__cnno': '3-105', 'degree': 76}, {'sno__name': '陆军', 'cno__cnno': '3-105', 'degree': 64}, {'sno__name': '匡明', 'cno__cnno': '3-105', 'degree': 91}, {'sno__name': '王芳', 'cno__cnno': '3-105', 'degree': 78}, {'sno__name': '王芳', 'cno__cnno': '6-166', 'degree': 81}, {'sno__name': '匡明', 'cno__cnno': '6-166', 'degree': 79}, {'sno__name': '陆军', 'cno__cnno': '6-166', 'degree': 85}]>
    
    
    

    15.查询所有学生的Sno, Cname和Degree列

    def sql_check(request):
        
        score = Score.objects.filter().values('sno__name','cno__name','degree')
        print(score)
        return HttpResponse('ok')
    打印结果显示:
    <QuerySet [{'sno__name': '陆军', 'cno__name': '操作系统', 'degree': 86}, {'sno__name': '匡明', 'cno__name': '操作系统', 'degree': 75}, {'sno__name': '王芳', 'cno__name': '操作系统', 'degree': 68}, {'sno__name': '陆军', 'cno__name': '计算机导论', 'degree': 92}, {'sno__name': '匡明', 'cno__name': '计算机导论', 'degree': 88}, {'sno__name': '王芳', 'cno__name': '计算机导论', 'degree': 76}, {'sno__name': '陆军', 'cno__name': '计算机导论', 'degree': 64}, {'sno__name': '匡明', 'cno__name': '计算机导论', 'degree': 91}, {'sno__name': '王芳', 'cno__name': '计算机导论', 'degree': 78}, {'sno__name': '王芳', 'cno__name': '数字电路', 'degree': 81}, {'sno__name': '匡明', 'cno__name': '数字电路', 'degree': 79}, {'sno__name': '陆军', 'cno__name': '数字电路', 'degree': 85}]>
    
    
    

    16.查询所有学生的Sname, Cname和Degree列

    def sql_check(request):
    
        score = Score.objects.filter().values('sno__name','cno__name','degree')
        print(score)
        return HttpResponse('ok')
        # 打印结果显示:
        <QuerySet [{'sno__name': '陆军', 'cno__name': '操作系统', 'degree': 86}, {'sno__name': '匡明', 'cno__name': '操作系统', 'degree': 75}, {'sno__name': '王芳', 'cno__name': '操作系统', 'degree': 68}, {'sno__name': '陆军', 'cno__name': '计算机导论', 'degree': 92}, {'sno__name': '匡明', 'cno__name': '计算机导论', 'degree': 88}, {'sno__name': '王芳', 'cno__name': '计算机导论', 'degree': 76}, {'sno__name': '陆军', 'cno__name': '计算机导论', 'degree': 64}, {'sno__name': '匡明', 'cno__name': '计算机导论', 'degree': 91}, {'sno__name': '王芳', 'cno__name': '计算机导论', 'degree': 78}, {'sno__name': '王芳', 'cno__name': '数字电路', 'degree': 81}, {'sno__name': '匡明', 'cno__name': '数字电路', 'degree': 79}, {'sno__name': '陆军', 'cno__name': '数字电路', 'degree': 85}]>
    

    17.查询'95031'班学生的平均分

    def sql_check(request):
        
        snos = Student.objects.filter(classes__cid='95031').values('sno')
        sno = [sno['sno'] for sno in snos]
        score = Score.objects.filter(sno__in=sno).values('sno').annotate(Avg('degree'))
        print(score)
        return HttpResponse('ok')
        # 打印结果显示:
        <QuerySet [{'sno': 103, 'degree__avg': 81.75}, {'sno': 105, 'degree__avg': 83.25}, {'sno': 109, 'degree__avg': 75.75}]>
    
    

    18.假设使用如下命令建立一个grdae表:

    create table grade(low int(3),upp int(3),rank char(1))
    insert into grade values(90,100,'A');
    insert into grade values(80,89,'B');
    insert into grade values(70,79,'C');
    insert into grade values(60,69,'D');
    insert into grade values(0,59,'E');
    现查询所有同学的Sno、Cno和rank列。

    
    --->解析学生的分值在90~100 之间为 'A' 80~89之间为'B'
    
    select Sno,Cno,rank
     from score,grade 
    where Degree between low and upp;
    --->最终结果显示:
    mysql> select Sno,Cno,rank
        ->  from score,grade 
        -> where Degree between low and upp;
    +-----+-------+------+
    | Sno | Cno   | rank |
    +-----+-------+------+
    | 103 | 3-245 | B    |
    | 105 | 3-245 | C    |
    | 109 | 3-245 | D    |
    | 103 | 3-105 | A    |
    | 105 | 3-105 | B    |
    | 109 | 3-105 | C    |
    | 103 | 3-105 | D    |
    | 105 | 3-105 | A    |
    | 109 | 3-105 | C    |
    | 103 | 6-166 | B    |
    | 105 | 6-166 | C    |
    | 109 | 6-166 | B    |
    +-----+-------+------+
    12 rows in set (0.00 sec)
    
    --->解法二:
    select   Sno, Cno,  (case when Degree between low and upp
              then rank else NULL end) as rank
    from score,grade
    where Sno in (select Sno from student) 
    having rank is not NULL;
    
    --->结果显示:
    mysql> select   Sno, Cno,  (case when Degree between low and upp
        ->           then rank else NULL end) as rank
        -> from score,grade
        -> where Sno in (select Sno from student) 
        -> having rank is not NULL;
    +-----+-------+------+
    | Sno | Cno   | rank |
    +-----+-------+------+
    | 103 | 3-245 | B    |
    | 105 | 3-245 | C    |
    | 109 | 3-245 | D    |
    | 103 | 3-105 | A    |
    | 105 | 3-105 | B    |
    | 109 | 3-105 | C    |
    | 103 | 3-105 | D    |
    | 105 | 3-105 | A    |
    | 109 | 3-105 | C    |
    | 103 | 6-166 | B    |
    | 105 | 6-166 | C    |
    | 109 | 6-166 | B    |
    +-----+-------+------+
    12 rows in set, 12 warnings (0.01 sec)
    
    

    19.查询选修'3-105'课程的成绩高于'109'号同学成绩的所有同学记录

    def sql_check(request):
        
        max_sno = Score.objects.filter(sno=109).values('sno').annotate(Max('degree'))[0]['degree__max']
        score01 = Score.objects.filter(Q(cno__cnno='3-105') & Q(degree__gt=max_sno)).values('sno','sno__name','degree')
        print(score01)
    
        return HttpResponse('ok')
        # 打印结果显示:
        <QuerySet [{'sno': 103, 'sno__name': '陆军', 'degree': 92}, {'sno': 105, 'sno__name': '匡明', 'degree': 88}, {'sno': 105, 'sno__name': '匡明', 'degree': 91}]>
    

    20.查询'计算机系'和'电子工程系'相同同职称的教师的Tname和Prof

    
    select Tname ,Prof from teacher where Prof = (select Prof from teacher  where Depart='计算机系' or Depart='电子工程系' group by Prof having count(1) >1);
    
    --->最终结果:
    mysql> select Tname ,Prof from teacher where Prof = (select Prof from teacher  where Depart='计算机系' or Depart='电子工程系' group by Prof having count(1) >1); 
    +--------+--------+
    | Tname  | Prof   |
    +--------+--------+
    | 王萍   | 助教   |
    | 刘冰   | 助教   |
    +--------+--------+
    2 rows in set (0.00 sec)
    
    

    21.查询成绩高于学号为'109',课程号为'3-105'的成绩的所有记录

    select *
    from score 
    where Cno='3-105' AND Degree >(select max(Degree) from score where Sno=109 );
    
    --->结果显示:
    mysql> select *
        -> from score 
        -> where Cno='3-105' AND Degree >(select max(Degree) from score where Sno=109 );
    +-----+-------+--------+
    | Sno | Cno   | Degree |
    +-----+-------+--------+
    | 103 | 3-105 |     92 |
    | 105 | 3-105 |     88 |
    | 105 | 3-105 |     91 |
    +-----+-------+--------+
    

    22.查询和学号为108,101的同学同年出生的所有学生的Sno,Sname和Sbirthday列

    select Sno,Sname,Sbirthday
    from student
    where year(Sbirthday) in 
    (select year(Sbirthday) from student where Sno=108 or Sno=101)
    having Sno != 108 and Sno != 101;
    
    --->最终结果显示:
    mysql> select Sno,Sname,Sbirthday
        -> from student
        -> where year(Sbirthday) in 
        -> (select year(Sbirthday) from student where Sno=108 or Sno=101)
        -> having Sno != 108 and Sno != 101;
    +-----+--------+---------------------+
    | Sno | Sname  | Sbirthday           |
    +-----+--------+---------------------+
    | 107 | 王丽   | 1976-01-23 00:00:00 |
    +-----+--------+---------------------+
    1 row in set (0.00 sec)
    
    

    23 .查询'张旭'教师任课的学生成绩

    select Sno, Degree
    from score,course
    where score.Cno = course.Cno AND Tno = (select Tno from teacher where Tname = '张旭');
    
    --->最终结果:
    mysql> select Sno, Degree
        -> from score,course
        -> where score.Cno = course.Cno AND Tno = (select Tno from teacher where Tname = '张旭');
    +-----+--------+
    | Sno | Degree |
    +-----+--------+
    | 103 |     85 |
    | 105 |     79 |
    | 109 |     81 |
    +-----+--------+
    3 rows in set (0.00 sec)
    

    24.查询选修某课程的同学人数多于5人的教师姓名

    select Tname 
    from teacher,course,score
    where teacher.Tno = course.Tno AND course.cno = score.cno
    group by score.Cno
    having count(1) > 5;   
    
    --->结果显示:
    mysql> select Tname ,count(1)
        -> from teacher,course,score
        -> where teacher.Tno = course.Tno AND course.cno = score.cno
        -> group by score.Cno;
    +--------+----------+
    | Tname  | count(1) |
    +--------+----------+
    | 王萍   |        6 |
    | 李诚   |        3 |
    | 张旭   |        3 |
    +--------+----------+
    3 rows in set (0.00 sec)
    
    --->最终结果显示:
    mysql> select Tname 
        -> from teacher,course,score
        -> where teacher.Tno = course.Tno AND course.cno = score.cno
        -> group by score.Cno
        -> having count(1) > 5;   
    +--------+
    | Tname  |
    +--------+
    | 王萍   |
    +--------+
    
    
    

    25.查询95033班和95031班全体学生的记录

    --->最终结果显示:
    mysql> select * from  student where  class in ('95033','95031');
    +-----+--------+------+---------------------+-------+
    | Sno | Sname  | Ssex | Sbirthday           | Class |
    +-----+--------+------+---------------------+-------+
    | 101 | 李军   | 男   | 1976-02-20 00:00:00 | 95033 |
    | 103 | 陆君   | 男   | 1974-06-03 00:00:00 | 95031 |
    | 105 | 匡明   | 男   | 1975-10-02 00:00:00 | 95031 |
    | 107 | 王丽   | 女   | 1976-01-23 00:00:00 | 95033 |
    | 108 | 曾华   | 男   | 1977-09-01 00:00:00 | 95033 |
    | 109 | 王芳   | 女   | 1975-02-10 00:00:00 | 95031 |
    +-----+--------+------+---------------------+-------+
    6 rows in set (0.00 sec)
    
    

    26.查询存在有85分以上成绩的课程Cno

    select Cno
    from score
    where Degree >85;
    
    --->最终结果显示:
    mysql> select Cno
        -> from score
        -> where Degree >85;
    +-------+
    | Cno   |
    +-------+
    | 3-245 |
    | 3-105 |
    | 3-105 |
    | 3-105 |
    +-------+
    

    27.查询出'计算机系'教师所教课程的成绩表

    select *
    from score where Cno in 
    (select Cno from course where Tno in
    (select Tno from teacher where Depart = '计算机系'));
    --->最终结果显示:
    mysql> select *
        -> from score where Cno in 
        -> (select Cno from course where Tno in
        -> (select Tno from teacher where Depart = '计算机系'));
    +-----+-------+--------+
    | Sno | Cno   | Degree |
    +-----+-------+--------+
    | 103 | 3-245 |     86 |
    | 105 | 3-245 |     75 |
    | 109 | 3-245 |     68 |
    | 103 | 3-105 |     92 |
    | 105 | 3-105 |     88 |
    | 109 | 3-105 |     76 |
    | 103 | 3-105 |     64 |
    | 105 | 3-105 |     91 |
    | 109 | 3-105 |     78 |
    +-----+-------+--------+
    9 rows in set (0.00 sec)
    

    28.查询'计算机系'和'电子工程系'不同职称的教师的Tname和Prof

    select any_value(Tname) Tname,Prof
    from teacher 
    where Depart='计算机系' or Depart='电子工程系'
    group by Prof
    having count(1) = 1;
    --->最终结果
    mysql> select any_value(Tname) Tname,Prof
        -> from teacher 
        -> where Depart='计算机系' or Depart='电子工程系'
        -> group by Prof
        -> having count(1) = 1;
    +--------+-----------+
    | Tname  | Prof      |
    +--------+-----------+
    | 李诚   | 副教授    |
    | 张旭   | 讲师      |
    +--------+-----------+
    
    --->解法二:
    mysql> select Tname,Prof from Teacher where Depart ='计算机系' and Prof  not in( select Prof from Teacher where Depart ='电子工程系') union select Tname,Prof from Teacher where Depart ='电子工程系' and Prof  not in( select Prof from Teacher where Depart ='计算机系');
    +--------+-----------+
    | Tname  | Prof      |
    +--------+-----------+
    | 李诚   | 副教授    |
    | 张旭   | 讲师      |
    +--------+-----------+
    

    29.查询选修编号为'3-105'课程且成绩至少高于选修编号为'3-245'的同学的Cno,Sname和Degree,并按照Degree降序排列

    any:代表括号中任意一个成绩就可以

    --->解析 至少高于 就是高于'3-245'成绩的最低分
    select distinct score.Cno,Sname,Degree
    from student, course,score
    where score.Cno = '3-105' AND student.Sno = score.Sno AND
    ( Degree > (select min(Degree) from score where Cno='3-245'))
     order by  Degree desc;
    
    --->最终结果显示:
    mysql> select distinct score.Cno,Sname,Degree
        -> from student, course,score
        -> where score.Cno = '3-105' AND student.Sno = score.Sno AND
        -> ( Degree > (select min(Degree) from score where Cno='3-245'))
        ->  order by  Degree desc;
    +-------+--------+--------+
    | Cno   | Sname  | Degree |
    +-------+--------+--------+
    | 3-105 | 陆君   |     92 |
    | 3-105 | 匡明   |     91 |
    | 3-105 | 匡明   |     88 |
    | 3-105 | 王芳   |     78 |
    | 3-105 | 王芳   |     76 |
    +-------+--------+--------+
    5 rows in set (0.00 sec)
    
    --->使用 any :相当于条件or
    select distinct score.Cno,Sname,Degree
    from student, course,score
    where score.Cno = '3-105' AND student.Sno = score.Sno AND
    ( Degree > any(select Degree from score where Cno='3-245'))
     order by  Degree desc;
    
    --->最终结果显示:
    mysql> select distinct score.Cno,Sname,Degree
        -> from student, course,score
        -> where score.Cno = '3-105' AND student.Sno = score.Sno AND
        -> ( Degree > any(select Degree from score where Cno='3-245'))
        ->  order by  Degree desc;
    +-------+--------+--------+
    | Cno   | Sname  | Degree |
    +-------+--------+--------+
    | 3-105 | 陆君   |     92 |
    | 3-105 | 匡明   |     91 |
    | 3-105 | 匡明   |     88 |
    | 3-105 | 王芳   |     78 |
    | 3-105 | 王芳   |     76 |
    +-------+--------+--------+
    
    
    

    30.查询选修编号为'3-105'且成绩高于选修编号为'3-245'课程的同学的Cno,Sname和Drgree

    all:代表括号中所有成绩

    ---->解析 高于'3-245'的成绩就是高于'3-245'成绩的最大值
    ----> all 相当于 and
    
    select distinct score.Cno,Sname,Degree
    from student, course,score
    where score.Cno = '3-105' AND student.Sno = score.Sno AND
    ( Degree > (select max(Degree) from score where Cno='3-245'))
     order by  Degree desc;
    
    # 上下两者类似
    
    select distinct score.Cno,Sname,Degree
    from student, course,score
    where score.Cno = '3-105' AND student.Sno = score.Sno AND
    ( Degree > all(select Degree from score where Cno='3-245'))
     order by  Degree desc;
    
    --->最终结果显示:
    mysql> select distinct score.Cno,Sname,Degree
        -> from student, course,score
        -> where score.Cno = '3-105' AND student.Sno = score.Sno AND
        -> ( Degree > all(select Degree from score where Cno='3-245'))
        ->  order by  Degree desc;
    +-------+--------+--------+
    | Cno   | Sname  | Degree |
    +-------+--------+--------+
    | 3-105 | 陆君   |     92 |
    | 3-105 | 匡明   |     91 |
    | 3-105 | 匡明   |     88 |
    +-------+--------+--------+
    

    31.查询所有教师和同学的name,sex和birthday

    --->解析 这里考察的是表的行拼接 需要使用 union
    select Sname name,Ssex sex,Sbirthday birthday
    from  student
    union
    select Tname,Tsex,Tbirthday
    from teacher; 
    
    --->最终结果显示:
    mysql> select Sname name,Ssex sex,Sbirthday birthday
        -> from  student
        -> union
        -> select Tname,Tsex,Tbirthday
        -> from teacher; 
    +-----------+-----+---------------------+
    | name      | sex | birthday            |
    +-----------+-----+---------------------+
    | 李军      | 男  | 1976-02-20 00:00:00 |
    | 陆君      | 男  | 1974-06-03 00:00:00 |
    | 匡明      | 男  | 1975-10-02 00:00:00 |
    | 王丽      | 女  | 1976-01-23 00:00:00 |
    | 曾华      | 男  | 1977-09-01 00:00:00 |
    | 王芳      | 女  | 1975-02-10 00:00:00 |
    | 李诚      | 男  | 1958-12-02 00:00:00 |
    | 王萍      | 女  | 1972-05-05 00:00:00 |
    | 刘冰      | 女  | 1977-08-14 00:00:00 |
    | 张旭      | 男  | 1969-03-12 00:00:00 |
    | 孙子衡    | 男  | 1990-05-24 00:00:00 |
    +-----------+-----+---------------------+
    11 rows in set (0.00 sec)
    

    32.查询所有'女'教师和'女'同学的name,sex和birthday

    select Sname name,Ssex sex,Sbirthday birthday
    from  student where Ssex='女'
    union
    select Tname,Tsex,Tbirthday
    from teacher where Tsex='女'; 
    
    --->最终结果显示:
    mysql> select Sname name,Ssex sex,Sbirthday birthday
        -> from  student where Ssex='女'
        -> union
        -> select Tname,Tsex,Tbirthday
        -> from teacher where Tsex='女'; 
    +--------+-----+---------------------+
    | name   | sex | birthday            |
    +--------+-----+---------------------+
    | 王丽   | 女  | 1976-01-23 00:00:00 |
    | 王芳   | 女  | 1975-02-10 00:00:00 |
    | 王萍   | 女  | 1972-05-05 00:00:00 |
    | 刘冰   | 女  | 1977-08-14 00:00:00 |
    +--------+-----+---------------------+
    
    

    33.查询成绩比该课程平均成绩低的同学的成绩表

    --->解法一:
    mysql> select * from score a  where degree < (select avg(degree) from score b where b.cno=a.cno);
    
    +-----+-------+--------+
    | Sno | Cno   | Degree |
    +-----+-------+--------+
    | 105 | 3-245 |     75 |
    | 109 | 3-245 |     68 |
    | 109 | 3-105 |     76 |
    | 103 | 3-105 |     64 |
    | 109 | 3-105 |     78 |
    | 105 | 6-166 |     79 |
    | 109 | 6-166 |     81 |
    +-----+-------+--------+
    7 rows in set (0.00 sec)
    
    --->解法二:
    --->解析先把各个课程的平均成绩拿出
    
    mysql> select Cno ,  AVG(Degree) Degree from score group by Cno;
    +-------+---------+
    | Cno   | Degree  |
    +-------+---------+
    | 3-105 | 81.5000 |
    | 3-245 | 76.3333 |
    | 6-166 | 81.6667 |
    +-------+---------+
    --->在让score表 和成绩表做连接  然后再对相同课程Degree 和平均成绩进行比较
    select Sno,score.Cno Cno ,score.Degree from score join
    (select Cno ,  AVG(Degree) Degree from score group by Cno) as s2
    on score.Cno = s2.Cno AND score.Degree <s2.Degree;
    
    --->最终结果显示:
    mysql> select Sno,score.Cno Cno ,score.Degree from score join
        -> (select Cno ,  AVG(Degree) Degree from score group by Cno) as s2
        -> on score.Cno = s2.Cno AND score.Degree <s2.Degree;
    +-----+-------+--------+
    | Sno | Cno   | Degree |
    +-----+-------+--------+
    | 105 | 3-245 |     75 |
    | 109 | 3-245 |     68 |
    | 109 | 3-105 |     76 |
    | 103 | 3-105 |     64 |
    | 109 | 3-105 |     78 |
    | 105 | 6-166 |     79 |
    | 109 | 6-166 |     81 |
    +-----+-------+--------+
    

    34.查询所有任课教师的Tname和Depart

    --->解析 就是有讲过课老师的Tname 和 Depart
    select Tname,Depart
    from teacher t,course c 
    where t.Tno = c.Tno AND c.Cno in (select Cno from score);
    
    --->最终结果显示:
    mysql> select Tname,Depart
        -> from teacher t,course c 
        -> where t.Tno = c.Tno AND c.Cno in (select Cno from score);
    +--------+-----------------+
    | Tname  | Depart          |
    +--------+-----------------+
    | 李诚   | 计算机系        |
    | 王萍   | 计算机系        |
    | 张旭   | 电子工程系      |
    +--------+-----------------+
    
    

    35.查询所有未讲课教师的Tname和Depart

    
    select Tname,Depart
    from teacher t,course c 
    where t.Tno = c.Tno AND c.Cno not in (select Cno from score);
    
    --->最终结果显示:
    mysql> select Tname,Depart
        -> from teacher t,course c 
        -> where t.Tno = c.Tno AND c.Cno not in (select Cno from score);
    +--------+-----------------+
    | Tname  | Depart          |
    +--------+-----------------+
    | 刘冰   | 电子工程系      |
    +--------+-----------------+
    1 row in set (0.00 sec)
    

    36.查询至少有2名男生的班号

    select Class
    from student 
    where Ssex = '男' group by Class
    having count(1) > 1;
    
    --->最终结果显示:
    mysql> select Class
        -> from student 
        -> where Ssex = '男' group by Class
        -> having count(1) > 1;
    +-------+
    | Class |
    +-------+
    | 95031 |
    | 95033 |
    +-------+
    

    37.查询student表中不姓''王''的同学记录

    select *
    from student
    where Sname not like '王%';
    
    --->最终结果显示:
    mysql> select *
        -> from student
        -> where Sname not like '王%';
    +-----+--------+------+---------------------+-------+
    | Sno | Sname  | Ssex | Sbirthday           | Class |
    +-----+--------+------+---------------------+-------+
    | 101 | 李军   | 男   | 1976-02-20 00:00:00 | 95033 |
    | 103 | 陆君   | 男   | 1974-06-03 00:00:00 | 95031 |
    | 105 | 匡明   | 男   | 1975-10-02 00:00:00 | 95031 |
    | 108 | 曾华   | 男   | 1977-09-01 00:00:00 | 95033 |
    +-----+--------+------+---------------------+-------+
    4 rows in set (0.00 sec)
    

    38.查询student表中每个学生的姓名和年龄

    select  Sname,
    year(now()) - year(Sbirthday) as age
    from student;
    --->最终结果显示:
    mysql> select  Sname,
        -> year(now()) - year(Sbirthday) as age
        -> from student;
    +--------+------+
    | Sname  | age  |
    +--------+------+
    | 李军   |   44 |
    | 陆君   |   46 |
    | 匡明   |   45 |
    | 王丽   |   44 |
    | 曾华   |   43 |
    | 王芳   |   45 |
    +--------+------+
    6 rows in set (0.00 sec)
    

    39.查询student表中最大和最小的Sbirthday日期值

    select max(Sbirthday),min(sbirthday) from student;
    
    --->最终结果:
    mysql> select max(Sbirthday),min(sbirthday) from student;
    +---------------------+---------------------+
    | max(Sbirthday)      | min(sbirthday)      |
    +---------------------+---------------------+
    | 1977-09-01 00:00:00 | 1974-06-03 00:00:00 |
    +---------------------+---------------------+
    1 row in set (0.00 sec)
    

    40.以班号和年龄从大到小的顺讯查询student表中的全部记录

    select *
    from student
    order by Class desc , Sbirthday;
    --->最终结果:
    mysql> select *
        -> from student
        -> order by Class desc , Sbirthday;
    +-----+--------+------+---------------------+-------+
    | Sno | Sname  | Ssex | Sbirthday           | Class |
    +-----+--------+------+---------------------+-------+
    | 107 | 王丽   | 女   | 1976-01-23 00:00:00 | 95033 |
    | 101 | 李军   | 男   | 1976-02-20 00:00:00 | 95033 |
    | 108 | 曾华   | 男   | 1977-09-01 00:00:00 | 95033 |
    | 103 | 陆君   | 男   | 1974-06-03 00:00:00 | 95031 |
    | 109 | 王芳   | 女   | 1975-02-10 00:00:00 | 95031 |
    | 105 | 匡明   | 男   | 1975-10-02 00:00:00 | 95031 |
    +-----+--------+------+---------------------+-------+
    6 rows in set (0.00 sec)
    

    41.查询'男'教师及其所上的课程

    select Tname,Cname
    from teacher t,course c
    where t.Tno = c.Tno;
    --->最终结果:
    mysql> select Tname,Cname
        -> from teacher t,course c
        -> where t.Tno = c.Tno;
    +--------+-----------------+
    | Tname  | Cname           |
    +--------+-----------------+
    | 王萍   | 计算机导论      |
    | 李诚   | 操作系统        |
    | 张旭   | 数字电路        |
    | 刘冰   | 高等数学        |
    +--------+-----------------+
    4 rows in set (0.00 sec)
    

    42.查询最高分同学的Sno,Cno和Degree列

    select Sno,Cno,Degree
    from score
    having Degree = (select max(Degree) from score);
    --->最终结果:
    mysql> select Sno,Cno,Degree
        -> from score
        -> having Degree = (select max(Degree) from score);
    +-----+-------+--------+
    | Sno | Cno   | Degree |
    +-----+-------+--------+
    | 103 | 3-105 |     92 |
    +-----+-------+--------+
    1 row in set (0.01 sec)
    
    

    43.查询和'李军'同性别的所有同学的Sname

    select Sname
    from student 
    where Ssex=(select Ssex from student where Sname='李军');
    
    --->最终结果:
    mysql> select Sname
        -> from student 
        -> where Ssex=(select Ssex from student where Sname='李军');
    +--------+
    | Sname  |
    +--------+
    | 李军   |
    | 陆君   |
    | 匡明   |
    | 曾华   |
    +--------+
    
    

    44.查询和'李军'同性别并同班的同学Sname

    select Sname
    from student 
    where (Class,Ssex) in(select Class,Ssex from student where Sname='李军');
    
    --->结果显示:
    
    mysql> select Sname
        -> from student 
        -> where (Class,Ssex) in(select Class,Ssex from student where Sname='李军'); 
    +--------+
    | Sname  |
    +--------+
    | 李军   |
    | 曾华   |
    +--------+
    
    

    45.查询所有选修'计算机导论'课程的'男'同学的成绩表

    select score.*
    from course,score,student
    where course.Cname = '计算机导论' AND course.Cno = score.Cno AND score.Sno = student.Sno AND student.Ssex = '男';
    
    ---> 最终结果:
    mysql> select score.*
        -> from course,score,student
        -> where course.Cname = '计算机导论' AND course.Cno = score.Cno AND score.Sno = student.Sno AND student.Ssex = '男';
    +-----+-------+--------+
    | Sno | Cno   | Degree |
    +-----+-------+--------+
    | 103 | 3-105 |     92 |
    | 103 | 3-105 |     64 |
    | 105 | 3-105 |     88 |
    | 105 | 3-105 |     91 |
    +-----+-------+--------+
    4 rows in set (0.00 sec)
    
    --->另一种解法:
    
    mysql> select  Sno,Cno,degree from score where Cno=( select Cno from course where Cname='计算机导论') and Sno in (select Sno from student where Ssex='男');
    +-----+-------+--------+
    | Sno | Cno   | degree |
    +-----+-------+--------+
    | 103 | 3-105 |     92 |
    | 103 | 3-105 |     64 |
    | 105 | 3-105 |     88 |
    | 105 | 3-105 |     91 |
    +-----+-------+--------+
    4 rows in set (0.00 sec)
    

    创表语句和插入语句

    #创建数据库:
    mysql> create database sql_exercise02 charset utf8;
    Query OK, 1 row affected (0.00 sec)
    
    mysql> use sql_exercise02;
    Database changed
    
    #建学生信息表student
    create table student
    (
    
    Sno varchar(20) not null primary key,
    Sname varchar(20) not null,
    Ssex varchar(20) not null,
    Sbirthday datetime,
    Class varchar(20)
    
    );
    #建立教师表
    create table teacher
    (
    Tno varchar(20) not null primary key,
    Tname varchar(20) not null,
    Tsex varchar(20) not null,
    Tbirthday datetime,
    Prof varchar(20),
    Depart varchar(20) not null
    
    );
    #建立课程表course
    create table course
    (
    Cno varchar(20) not null primary key,
    Cname varchar(20) not null,
    Tno varchar(20) not null,
    foreign key(Tno) references teacher(Tno)
    
    );
    #建立成绩表
    create table score
    (
    Sno varchar(20) not null ,
    foreign key(Sno) references student(Sno),
    Cno varchar(20) not null,
    foreign key(Cno) references course(Cno),
    Degree decimal
    
    );
    
    #添加学生信息
    insert into student values('108','曾华','男','1977-09-01','95033');
    insert into student values('105','匡明','男','1975-10-02','95031');
    insert into student values('107','王丽','女','1976-01-23','95033');
    insert into student values('101','李军','男','1976-02-20','95033');
    insert into student values('109','王芳','女','1975-02-10','95031');
    insert into student values('103','陆君','男','1974-06-03','95031');
    
    #添加教师表
    insert into teacher values('804','李诚','男','1958-12-02','副教授','计算机系');
    insert into teacher values('856','张旭','男','1969-03-12','讲师','电子工程系');
    insert into teacher values('825','王萍','女','1972-05-05','助教','计算机系');
    insert into teacher values('831','刘冰','女','1977-08-14','助教','电子工程系');
    
    #添加课程表
    insert into course values('3-105','计算机导论','825');
    insert into course values('3-245','操作系统','804');
    insert into course values('6-166','数字电路','856');
    insert into course values('9-888','高等数学','831');
    #添加成绩表
    
    insert into score values('103','3-245','86');
    insert into score values('105','3-245','75');
    insert into score values('109','3-245','68');
    insert into score values('103','3-105','92');
    insert into score values('105','3-105','88');
    insert into score values('109','3-105','76');
    insert into score values('103','3-105','64');
    insert into score values('105','3-105','91');
    insert into score values('109','3-105','78');
    insert into score values('103','6-166','85');
    insert into score values('105','6-166','79');
    insert into score values('109','6-166','81');
    
    

    相关文章

      网友评论

          本文标题:Django ORM查询练习题45题(初级)

          本文链接:https://www.haomeiwen.com/subject/pqyotltx.html