[SQL]学生、课程、选课,查询选择所有/3门以上课程的学生

/*
SQLyog Community Edition- MySQL GUI v6.13
MySQL - 5.0.45-community-nt : Database - test
*********************************************************************
*/



/*!40101 SET NAMES utf8 */ ;

/*!40101 SET SQL_MODE=''*/ ;

create   database   if   not   exists  `test`;

USE  `test`;

/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */ ;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */ ;

/*Table structure for table `c` */

DROP   TABLE   IF   EXISTS  `c`;

CREATE   TABLE  `c` (
  `cid` 
char ( 10 NOT   NULL ,
  `cname` 
char ( 20 default   NULL ,
  
PRIMARY   KEY   (`cid`)
) ENGINE
= InnoDB  DEFAULT  CHARSET = gb2312;

/*Data for the table `c` */

insert    into  `c`(`cid`,`cname`)  values  ( ' 001 ' , ' b1 ' ),( ' 002 ' , ' b2 ' ),( ' 003 ' , ' b3 ' ),( ' 004 ' , ' b4 ' ),( ' 005 ' , ' b5 ' );

/*Table structure for table `s` */

DROP   TABLE   IF   EXISTS  `s`;

CREATE   TABLE  `s` (
  `sid` 
char ( 10 NOT   NULL ,
  `sname` 
char ( 20 default   NULL ,
  
PRIMARY   KEY   (`sid`)
) ENGINE
= InnoDB  DEFAULT  CHARSET = gb2312;

/*Data for the table `s` */

insert    into  `s`(`sid`,`sname`)  values  ( ' 001 ' , ' a ' ),( ' 002 ' , ' b ' ),( ' 003 ' , ' c ' ),( ' 004 ' , ' d ' ),( ' 005 ' , ' e ' ),( ' 006 ' , ' f ' );

/*Table structure for table `sc` */

DROP   TABLE   IF   EXISTS  `sc`;

CREATE   TABLE  `sc` (
  `sid` 
char ( 10 NOT   NULL ,
  `cid` 
char ( 10 NOT   NULL ,
  
KEY  `sid` (`sid`),
  
KEY  `cid` (`cid`),
  
CONSTRAINT  `sc_ibfk_1`  FOREIGN   KEY  (`sid`)  REFERENCES  `s` (`sid`),
  
CONSTRAINT  `sc_ibfk_2`  FOREIGN   KEY  (`cid`)  REFERENCES  `c` (`cid`)
) ENGINE
= InnoDB  DEFAULT  CHARSET = gb2312;

/*Data for the table `sc` */

insert    into  `sc`(`sid`,`cid`)  values  ( ' 001 ' , ' 001 ' ),( ' 001 ' , ' 002 ' ),( ' 001 ' , ' 003 ' ),( ' 001 ' , ' 004 ' ),( ' 001 ' , ' 005 ' ),( ' 002 ' , ' 002 ' ),( ' 002 ' , ' 003 ' ),( ' 002 ' , ' 005 ' ),( ' 003 ' , ' 001 ' ),( ' 003 ' , ' 002 ' ),( ' 003 ' , ' 004 ' ),( ' 003 ' , ' 005 ' );

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */ ;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */ ;

查询选择了所有课程的学生
select  s.sid,s.sname 
from  s, 
     (
select  sc.sid  from  sc  group   by  sid  having   count ( * ) = ( select   count ( * from  c)) 
      
as  tmp
where  s.sid = tmp.sid


查询选择了超过3门以上课程的学生
select  s.sid,s.sname 
from  s, 
     (
select  sc.sid  from  sc  group   by  sid  having   count ( * ) > 3
      
as  tmp
where  s.sid = tmp.sid

你可能感兴趣的:(sql,c,table,null,database,insert)