• 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');
  • 相关阅读:
    C++中用Int转成bool时,只有0是false,其他都是true。这个和其他语言很不一样,注意不要掉坑里了。
    C# 获取动态验证码?
    Silverlight单元格事件
    LDAPHelper
    Perl内部保留变量(系统变量)
    WebSphere MQ基础命令
    老鼠, 老虎傻傻分不清楚之Double.NaN
    TextBlock or Label?
    如何阅读代码
    EDID
  • 原文地址:https://www.cnblogs.com/moris5013/p/9644581.html
Copyright © 2020-2023  润新知