zoukankan      html  css  js  c++  java
  • sql中的exists用法

    查询选修语文(cno=21)的学生名单

    SELECT sname  FROM student  WHERE  EXISTS ( SELECT 1 FROM  sc  WHERE sc.cno = 21 AND  sc.sno  =  student.sno )

    查询没有选修语文(cno=21)的学生名单

    SELECT sname  FROM student  WHERE NOT EXISTS ( SELECT 1 FROM  sc  WHERE sc.cno = 21 AND  sc.sno  =  student.sno )

    选修全部课程的学生名单  (子查询)

    SELECT sname  FROM student  WHERE sno  in  (
    
    SELECT sc.sno  FROM  sc   GROUP BY  sc.sno  HAVING  count(1) =  (SELECT count(1) from course)
    
    )

    选修全部课程的学生名单 (exists)

    select * from student t where not exists 
    ( select * from course s where not exists 
          (select * from sc where t.sno=sc.sno and s.cno= sc.cno   )
    )
    

     当有课程没有选修时,下面的查询有返回的记录数。当全部课程都选择时,返回空

    ( select * from course s where not exists
          (select * from sc where t.sno=sc.sno and s.cno= sc.cno )
    )

    数据库表结构

    --课程表
    CREATE TABLE `course` (
      `cno` int(11) NOT NULL DEFAULT '0',
      `cname` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`cno`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
    
    INSERT INTO `course` VALUES ('20', '数学');
    INSERT INTO `course` VALUES ('21', '语文');
    INSERT INTO `course` VALUES ('22', '外语');
    
    --课程学生表
    CREATE TABLE `sc` (
      `sno` int(11) NOT NULL DEFAULT '0',
      `cno` int(11) NOT NULL DEFAULT '0',
      PRIMARY KEY (`sno`,`cno`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
    
    INSERT INTO `sc` VALUES ('10', '20');
    INSERT INTO `sc` VALUES ('10', '21');
    INSERT INTO `sc` VALUES ('11', '20');
    INSERT INTO `sc` VALUES ('11', '21');
    INSERT INTO `sc` VALUES ('11', '22');
    INSERT INTO `sc` VALUES ('12', '22');
    
    --学生表
    CREATE TABLE `student` (
      `sno` int(11) NOT NULL DEFAULT '0',
      `sname` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`sno`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
    
    INSERT INTO `student` VALUES ('10', 'zhangsan');
    INSERT INTO `student` VALUES ('11', 'lisi');
    INSERT INTO `student` VALUES ('12', 'wangwu');
  • 相关阅读:
    做好测试计划和测试用例的工作的关键是什么?
    windows创建虚拟环境
    面试题整理
    【爬虫】使用selenium设置cookie
    【爬虫】随机获取UA
    Scrapy爬虫提高效率
    【爬虫】多线程爬取糗事百科写入文件
    【爬虫】多线程爬取表情包
    【爬虫】Condition版的生产者和消费者模式
    【爬虫】Load版的生产者和消费者模式
  • 原文地址:https://www.cnblogs.com/moris5013/p/9644581.html
Copyright © 2011-2022 走看看