python--MySql(外键约束、多表查询(*****))

两张表之间的关系:

  • 一对一(两张表可以合并成一张表)
    一对一用的比较少,多对一对外键设置unique约束可以实现一对一
  • 一对多(例如:每一个班主任会对应多个学生 , 而每个学生只能对应一个班主任
  • 多对多
    多对多得创建第三张表
    第三张表中创建两个外键
    多对多表的创建:详见博客结尾

外键约束

  创建外键

    举个栗子:

---  每一个班主任会对应多个学生 , 而每个学生只能对应一个班主任
---  主表
CREATE TABLE classcharger(

       id TINYINT auto_increment,
       name VARCHAR (20),
       age INT ,
       is_marriged boolean  -- show create table ClassCharger: tinyint(1)

);

INSERT INTO classcharger (name,age,is_marriged) VALUES ("mary",24,0),
                                                       ("kaylee",25,0),
                                                       ("lily",30,0),
                                                       ("rain",28,0);
----子表

CREATE TABLE Student(

       id INT auto_increment,
       name VARCHAR (20),
       charger_id TINYINT,     --切记:作为外键一定要和关联主键的数据类型保持一致
       -- [ADD CONSTRAINT charger_fk_stu]FOREIGN KEY (charger_id) REFERENCES classcharger(id)

);

INSERT INTO Student(name,charger_id) VALUES ("alvin",2),
                                            ("vida",1),
                                            ("fenqi",3),
                                            ("rida",1),
                                            ("aily",4),
                                            ("ruiqi",3);
mysql> select * from classcharger;
+----+--------+------+------------+
| id | name   | age  | is_married |
+----+--------+------+------------+
|  1 | mary   |   24 |          0 |
|  2 | kaylee |   25 |          0 |
|  3 | lily   |   30 |          0 |
|  4 | rain   |   28 |          0 |
+----+--------+------+------------+
4 rows in set (0.00 sec)

mysql> select * from student;
+----+-------+------------+
| id | name  | charger_id |
+----+-------+------------+
|  1 | alvin |          2 |
|  2 | vida  |          1 |
|  3 | fenqi |          3 |
|  4 | rida  |          1 |
|  5 | aily  |          4 |
|  6 | ruiqi |          3 |
+----+-------+------------+
6 rows in set (0.00 sec)

删除名字为‘Mary’的班主任不成功,原因是子表的外键‘charger_id’关联主表的‘id’键。

-----------增加外键和删除外键---------

mysql> alter table student add constraint abc
    ->                     foreign key(charger_id)
    ->                     references classcharger(id);
Query OK, 6 rows affected (2.59 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> alter table student drop foreign key abc;
Query OK, 0 rows affected (0.20 sec)
Records: 0  Duplicates: 0  Warnings: 0

多表查询(重要度*****)

  准备表

-- 准备两张表
-- employee
-- department

mysql> create table employee(
    -> emp_id int auto_increment primary key not null,
    -> emp_name varchar(50),
    -> age int,
    -> dep_id int);
Query OK, 0 rows affected (0.73 sec)

mysql> insert into employee(emp_name,age,dep_id) values
    -> ('A',19,200),
    -> ('B',26,201),
    -> ('C',30,201),
    -> ('D',24,202),
    -> ('E',20,200),
    -> ('F',38,204);
Query OK, 6 rows affected (0.23 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> create table department(
    -> dep_id int,
    -> dep_name varchar(100)
    -> );
Query OK, 0 rows affected (0.52 sec)

mysql> insert into department values(200,'HR'),
    -> (201,'TEC'),
    -> (202,'SALE'),
    -> (203,'FINANCE');
Query OK, 4 rows affected (0.12 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from employee;
+--------+----------+------+--------+
| emp_id | emp_name | age  | dep_id |
+--------+----------+------+--------+
|      1 | A        |   19 |    200 |
|      2 | B        |   26 |    201 |
|      3 | C        |   30 |    201 |
|      4 | D        |   24 |    202 |
|      5 | E        |   20 |    200 |
|      6 | F        |   38 |    204 |
+--------+----------+------+--------+
6 rows in set (0.00 sec)

mysql> select * from department;
+--------+----------+
| dep_id | dep_name |
+--------+----------+
|    200 | HR       |
|    201 | TEC      |
|    202 | SALE     |
|    203 | FINANCE  |
+--------+----------+
4 rows in set (0.00 sec)


多表查询值连接查询

1.笛卡尔积查询

mysql> select * from employee,department;
+--------+----------+------+--------+--------+----------+
| emp_id | emp_name | age  | dep_id | dep_id | dep_name |
+--------+----------+------+--------+--------+----------+
|      1 | A        |   19 |    200 |    200 | HR       |
|      1 | A        |   19 |    200 |    201 | TEC      |
|      1 | A        |   19 |    200 |    202 | SALE     |
|      1 | A        |   19 |    200 |    203 | FINANCE  |
|      2 | B        |   26 |    201 |    200 | HR       |
|      2 | B        |   26 |    201 |    201 | TEC      |
|      2 | B        |   26 |    201 |    202 | SALE     |
|      2 | B        |   26 |    201 |    203 | FINANCE  |
|      3 | C        |   30 |    201 |    200 | HR       |
|      3 | C        |   30 |    201 |    201 | TEC      |
|      3 | C        |   30 |    201 |    202 | SALE     |
|      3 | C        |   30 |    201 |    203 | FINANCE  |
|      4 | D        |   24 |    202 |    200 | HR       |
|      4 | D        |   24 |    202 |    201 | TEC      |
|      4 | D        |   24 |    202 |    202 | SALE     |
|      4 | D        |   24 |    202 |    203 | FINANCE  |
|      5 | E        |   20 |    200 |    200 | HR       |
|      5 | E        |   20 |    200 |    201 | TEC      |
|      5 | E        |   20 |    200 |    202 | SALE     |
|      5 | E        |   20 |    200 |    203 | FINANCE  |
|      6 | F        |   38 |    204 |    200 | HR       |
|      6 | F        |   38 |    204 |    201 | TEC      |
|      6 | F        |   38 |    204 |    202 | SALE     |
|      6 | F        |   38 |    204 |    203 | FINANCE  |
+--------+----------+------+--------+--------+----------+
24 rows in set (0.00 sec)

--employee有6条记录,department有4条记录,select * from employee,department;语句得到的结果是6*4=24条记录,很显然多了很多我们不需要的无关项

--我们只关心employee表中dep_id和department表中相同的dep_id字段。

2.内连接

-- 查询两张表中都有的关联数据,相当于利用条件从笛卡尔积结果中筛选出了正确的结果。

mysql> select * from employee,department where employee.dep_id=department.dep_id
;
+--------+----------+------+--------+--------+----------+
| emp_id | emp_name | age  | dep_id | dep_id | dep_name |
+--------+----------+------+--------+--------+----------+
|      1 | A        |   19 |    200 |    200 | HR       |
|      2 | B        |   26 |    201 |    201 | TEC      |
|      3 | C        |   30 |    201 |    201 | TEC      |
|      4 | D        |   24 |    202 |    202 | SALE     |
|      5 | E        |   20 |    200 |    200 | HR       |
+--------+----------+------+--------+--------+----------+
5 rows in set (0.00 sec)

mysql> select * from employee inner join department on employee.dep_id=departmen
t.dep_id;
+--------+----------+------+--------+--------+----------+
| emp_id | emp_name | age  | dep_id | dep_id | dep_name |
+--------+----------+------+--------+--------+----------+
|      1 | A        |   19 |    200 |    200 | HR       |
|      2 | B        |   26 |    201 |    201 | TEC      |
|      3 | C        |   30 |    201 |    201 | TEC      |
|      4 | D        |   24 |    202 |    202 | SALE     |
|      5 | E        |   20 |    200 |    200 | HR       |
+--------+----------+------+--------+--------+----------+
5 rows in set (0.00 sec)

--很显然 select * from employee,department where employee.dep_id=department.dep_id;
--和 select * from employee inner join department on employee.dep_id=department.dep_id;

--这两条语句得到的结果一样,推荐使用:
--select * from employee inner join department on employee.dep_id=department.dep_id;

3.外连接

--(1)左外连接:在内连接的基础上增加左边有右边没有的结果
mysql> select * from employee left join department on employee.dep_id=department
.dep_id;
+--------+----------+------+--------+--------+----------+
| emp_id | emp_name | age  | dep_id | dep_id | dep_name |
+--------+----------+------+--------+--------+----------+
|      1 | A        |   19 |    200 |    200 | HR       |
|      5 | E        |   20 |    200 |    200 | HR       |
|      2 | B        |   26 |    201 |    201 | TEC      |
|      3 | C        |   30 |    201 |    201 | TEC      |
|      4 | D        |   24 |    202 |    202 | SALE     |
|      6 | F        |   38 |    204 |   NULL | NULL     |
+--------+----------+------+--------+--------+----------+
6 rows in set (0.00 sec)
--(2)右外连接:在内连接的基础上增加右边有左边没有的结果
mysql> select * from employee right join department on employee.dep_id=departmen
t.dep_id;
+--------+----------+------+--------+--------+----------+
| emp_id | emp_name | age  | dep_id | dep_id | dep_name |
+--------+----------+------+--------+--------+----------+
|      1 | A        |   19 |    200 |    200 | HR       |
|      2 | B        |   26 |    201 |    201 | TEC      |
|      3 | C        |   30 |    201 |    201 | TEC      |
|      4 | D        |   24 |    202 |    202 | SALE     |
|      5 | E        |   20 |    200 |    200 | HR       |
|   NULL | NULL     | NULL |   NULL |    203 | FINANCE  |
+--------+----------+------+--------+--------+----------+
6 rows in set (0.00 sec)
--(3)全外连接:在内连接的基础上增加左边有右边没有的和右边有左边没有的结果
-- mysql不支持全外连接 full JOIN
-- mysql可以使用此种方式间接实现全外连接
mysql> select * from employee right join department on employee.dep_id=departmen
t.dep_id union
    -> select * from employee left join department on employee.dep_id=department
.dep_id;
+--------+----------+------+--------+--------+----------+
| emp_id | emp_name | age  | dep_id | dep_id | dep_name |
+--------+----------+------+--------+--------+----------+
|      1 | A        |   19 |    200 |    200 | HR       |
|      2 | B        |   26 |    201 |    201 | TEC      |
|      3 | C        |   30 |    201 |    201 | TEC      |
|      4 | D        |   24 |    202 |    202 | SALE     |
|      5 | E        |   20 |    200 |    200 | HR       |
|   NULL | NULL     | NULL |   NULL |    203 | FINANCE  |
|      6 | F        |   38 |    204 |   NULL | NULL     |
+--------+----------+------+--------+--------+----------+

 -- 注意 union与union all的区别:union会去掉相同的纪录

多表查询之复合条件连接查询

-- 查询员工年龄大于等于25岁的部门

mysql> select distinct dep_name
    -> from employee,department
    -> where employee.dep_id=department.dep_id
    -> and age>25;
+----------+
| dep_name |
+----------+
| TEC      |
+----------+
1 row in set (0.00 sec)


--以内连接的方式查询employee和department表,并且以age字段的降序方式显示
mysql> select * from employee inner join department
    -> on employee.dep_id=department.dep_id
    -> order by age desc;
+--------+----------+------+--------+--------+----------+
| emp_id | emp_name | age  | dep_id | dep_id | dep_name |
+--------+----------+------+--------+--------+----------+
|      3 | C        |   30 |    201 |    201 | TEC      |
|      2 | B        |   26 |    201 |    201 | TEC      |
|      4 | D        |   24 |    202 |    202 | SALE     |
|      5 | E        |   20 |    200 |    200 | HR       |
|      1 | A        |   19 |    200 |    200 | HR       |
+--------+----------+------+--------+--------+----------+
5 rows in set (0.00 sec)

多表查询之子查询

-- 子查询是将一个查询语句嵌套在另一个查询语句中。
-- 内层查询语句的查询结果,可以为外层查询语句提供查询条件。
-- 子查询中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等关键字
-- 还可以包含比较运算符:= 、 !=、> 、<等
-- 1. 带IN关键字的子查询

   ---查询employee表,但dep_id必须在department表中出现过
mysql> select * from employee where dep_id in
    -> (select dep_id from department);
+--------+----------+------+--------+
| emp_id | emp_name | age  | dep_id |
+--------+----------+------+--------+
|      1 | A        |   19 |    200 |
|      2 | B        |   26 |    201 |
|      3 | C        |   30 |    201 |
|      4 | D        |   24 |    202 |
|      5 | E        |   20 |    200 |
+--------+----------+------+--------+
5 rows in set (0.00 sec)

-- 2. 带比较运算符的子查询

-- =、!=、>、>=、<、<=、<> !=
 -- 查询员工年龄大于等于25岁的部门
mysql> select dep_name from department where dep_id in
    -> (select distinct dep_id from employee where age>25);
+----------+
| dep_name |
+----------+
| TEC      |
+----------+
1 row in set (0.00 sec)
-- 3. 带EXISTS关键字的子查询
-- EXISTS关字键字表示存在。在使用EXISTS关键字时,内层查询语句不返回查询的记录。
-- 而是返回一个真假值。Ture或False
-- 当返回Ture时,外层查询语句将进行查询;当返回值为False时,外层查询语句不进行查询
mysql> select * from employee
    -> where exists
    -> (select dep_name from department where dep_id=203); --内层语句返回True
+--------+----------+------+--------+
| emp_id | emp_name | age  | dep_id |
+--------+----------+------+--------+
|      1 | A        |   19 |    200 |
|      2 | B        |   26 |    201 |
|      3 | C        |   30 |    201 |
|      4 | D        |   24 |    202 |
|      5 | E        |   20 |    200 |
|      6 | F        |   38 |    204 |
+--------+----------+------+--------+
6 rows in set (0.00 sec)

mysql> select * from employee
    -> where exists
    -> (select dep_name from department where dep_id=205); --内层语句返回False
Empty set (0.00 sec)

练习

数据导入:

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 50624
 Source Host           : localhost
 Source Database       : sqlexam

 Target Server Type    : MySQL
 Target Server Version : 50624
 File Encoding         : utf-8

 Date: 10/21/2016 06:46:46 AM
*/

SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
--  Table structure for `class`
-- ----------------------------
DROP TABLE IF EXISTS `class`;
CREATE TABLE `class` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `caption` varchar(32) NOT NULL,
  PRIMARY KEY (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `class`
-- ----------------------------
BEGIN;
INSERT INTO `class` VALUES ('1', '三年二班'), ('2', '三年三班'), ('3', '一年二班'), ('4', '二年九班');
COMMIT;

-- ----------------------------
--  Table structure for `course`
-- ----------------------------
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `cname` varchar(32) NOT NULL,
  `teacher_id` int(11) NOT NULL,
  PRIMARY KEY (`cid`),
  KEY `fk_course_teacher` (`teacher_id`),
  CONSTRAINT `fk_course_teacher` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `course`
-- ----------------------------
BEGIN;
INSERT INTO `course` VALUES ('1', '生物', '1'), ('2', '物理', '2'), ('3', '体育', '3'), ('4', '美术', '2');
COMMIT;

-- ----------------------------
--  Table structure for `score`
-- ----------------------------
DROP TABLE IF EXISTS `score`;
CREATE TABLE `score` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` int(11) NOT NULL,
  `course_id` int(11) NOT NULL,
  `num` int(11) NOT NULL,
  PRIMARY KEY (`sid`),
  KEY `fk_score_student` (`student_id`),
  KEY `fk_score_course` (`course_id`),
  CONSTRAINT `fk_score_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`cid`),
  CONSTRAINT `fk_score_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`sid`)
) ENGINE=InnoDB AUTO_INCREMENT=53 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `score`
-- ----------------------------
BEGIN;
INSERT INTO `score` VALUES ('1', '1', '1', '10'), ('2', '1', '2', '9'), ('5', '1', '4', '66'), ('6', '2', '1', '8'), ('8', '2', '3', '68'), ('9', '2', '4', '99'), ('10', '3', '1', '77'), ('11', '3', '2', '66'), ('12', '3', '3', '87'), ('13', '3', '4', '99'), ('14', '4', '1', '79'), ('15', '4', '2', '11'), ('16', '4', '3', '67'), ('17', '4', '4', '100'), ('18', '5', '1', '79'), ('19', '5', '2', '11'), ('20', '5', '3', '67'), ('21', '5', '4', '100'), ('22', '6', '1', '9'), ('23', '6', '2', '100'), ('24', '6', '3', '67'), ('25', '6', '4', '100'), ('26', '7', '1', '9'), ('27', '7', '2', '100'), ('28', '7', '3', '67'), ('29', '7', '4', '88'), ('30', '8', '1', '9'), ('31', '8', '2', '100'), ('32', '8', '3', '67'), ('33', '8', '4', '88'), ('34', '9', '1', '91'), ('35', '9', '2', '88'), ('36', '9', '3', '67'), ('37', '9', '4', '22'), ('38', '10', '1', '90'), ('39', '10', '2', '77'), ('40', '10', '3', '43'), ('41', '10', '4', '87'), ('42', '11', '1', '90'), ('43', '11', '2', '77'), ('44', '11', '3', '43'), ('45', '11', '4', '87'), ('46', '12', '1', '90'), ('47', '12', '2', '77'), ('48', '12', '3', '43'), ('49', '12', '4', '87'), ('52', '13', '3', '87');
COMMIT;

-- ----------------------------
--  Table structure for `student`
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `gender` char(1) NOT NULL,
  `class_id` int(11) NOT NULL,
  `sname` varchar(32) NOT NULL,
  PRIMARY KEY (`sid`),
  KEY `fk_class` (`class_id`),
  CONSTRAINT `fk_class` FOREIGN KEY (`class_id`) REFERENCES `class` (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `student`
-- ----------------------------
BEGIN;
INSERT INTO `student` VALUES ('1', '男', '1', '理解'), ('2', '女', '1', '钢蛋'), ('3', '男', '1', '张三'), ('4', '男', '1', '张一'), ('5', '女', '1', '张二'), ('6', '男', '1', '张四'), ('7', '女', '2', '铁锤'), ('8', '男', '2', '李三'), ('9', '男', '2', '李一'), ('10', '女', '2', '李二'), ('11', '男', '2', '李四'), ('12', '女', '3', '如花'), ('13', '男', '3', '刘三'), ('14', '男', '3', '刘一'), ('15', '女', '3', '刘二'), ('16', '男', '3', '刘四');
COMMIT;

-- ----------------------------
--  Table structure for `teacher`
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher` (
  `tid` int(11) NOT NULL AUTO_INCREMENT,
  `tname` varchar(32) NOT NULL,
  PRIMARY KEY (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `teacher`
-- ----------------------------
BEGIN;
INSERT INTO `teacher` VALUES ('1', '张磊老师'), ('2', '李平老师'), ('3', '刘海燕老师'), ('4', '朱云海老师'), ('5', '李杰老师');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

 创建好的五张表

mysql> select * from class;
+-----+----------+
| cid | caption  |
+-----+----------+
|   1 | 三年二班 |
|   2 | 三年三班 |
|   3 | 一年二班 |
|   4 | 二年九班 |
+-----+----------+
4 rows in set (0.05 sec)

--------------------------------------------------------------------------

mysql> select * from course;
+-----+-------+------------+
| cid | cname | teacher_id |
+-----+-------+------------+
|   1 | 生物  |          1 |
|   2 | 物理  |          2 |
|   3 | 体育  |          3 |
|   4 | 美术  |          2 |
+-----+-------+------------+
4 rows in set (0.05 sec)

----------------------------------------

mysql> select * from score;
+-----+------------+-----------+-----+
| sid | student_id | course_id | num |
+-----+------------+-----------+-----+
|   1 |          1 |         1 |  10 |
|   2 |          1 |         2 |   9 |
|   5 |          1 |         4 |  66 |
|   6 |          2 |         1 |   8 |
|   8 |          2 |         3 |  68 |
|   9 |          2 |         4 |  99 |
|  10 |          3 |         1 |  77 |
|  11 |          3 |         2 |  66 |
|  12 |          3 |         3 |  87 |
|  13 |          3 |         4 |  99 |
|  14 |          4 |         1 |  79 |
|  15 |          4 |         2 |  11 |
|  16 |          4 |         3 |  67 |
|  17 |          4 |         4 | 100 |
|  18 |          5 |         1 |  79 |
|  19 |          5 |         2 |  11 |
|  20 |          5 |         3 |  67 |
|  21 |          5 |         4 | 100 |
|  22 |          6 |         1 |   9 |
|  23 |          6 |         2 | 100 |
|  24 |          6 |         3 |  67 |
|  25 |          6 |         4 | 100 |
|  26 |          7 |         1 |   9 |
|  27 |          7 |         2 | 100 |
|  28 |          7 |         3 |  67 |
|  29 |          7 |         4 |  88 |
|  30 |          8 |         1 |   9 |
|  31 |          8 |         2 | 100 |
|  32 |          8 |         3 |  67 |
|  33 |          8 |         4 |  88 |
|  34 |          9 |         1 |  91 |
|  35 |          9 |         2 |  88 |
|  36 |          9 |         3 |  67 |
|  37 |          9 |         4 |  22 |
|  38 |         10 |         1 |  90 |
|  39 |         10 |         2 |  77 |
|  40 |         10 |         3 |  43 |
|  41 |         10 |         4 |  87 |
|  42 |         11 |         1 |  90 |
|  43 |         11 |         2 |  77 |
|  44 |         11 |         3 |  43 |
|  45 |         11 |         4 |  87 |
|  46 |         12 |         1 |  90 |
|  47 |         12 |         2 |  77 |
|  48 |         12 |         3 |  43 |
|  49 |         12 |         4 |  87 |
|  52 |         13 |         3 |  87 |
+-----+------------+-----------+-----+
47 rows in set (0.00 sec)

--------------------------------------------------------

mysql> select * from student;
+-----+--------+----------+-------+
| sid | gender | class_id | sname |
+-----+--------+----------+-------+
|   1 | 男     |        1 | 理解  |
|   2 | 女     |        1 | 钢蛋  |
|   3 | 男     |        1 | 张三  |
|   4 | 男     |        1 | 张一  |
|   5 | 女     |        1 | 张二  |
|   6 | 男     |        1 | 张四  |
|   7 | 女     |        2 | 铁锤  |
|   8 | 男     |        2 | 李三  |
|   9 | 男     |        2 | 李一  |
|  10 | 女     |        2 | 李二  |
|  11 | 男     |        2 | 李四  |
|  12 | 女     |        3 | 如花  |
|  13 | 男     |        3 | 刘三  |
|  14 | 男     |        3 | 刘一  |
|  15 | 女     |        3 | 刘二  |
|  16 | 男     |        3 | 刘四  |
+-----+--------+----------+-------+
16 rows in set (0.00 sec)

-----------------------------------------------

mysql> select * from teacher;
+-----+------------+
| tid | tname      |
+-----+------------+
|   1 | 张磊老师   |
|   2 | 李平老师   |
|   3 | 刘海燕老师 |
|   4 | 朱云海老师 |
|   5 | 李杰老师   |
+-----+------------+
5 rows in set (0.00 sec)

基于以上五张表查询:

1、将所有的课程的名称以及对应的任课老师姓名打印出来,如下:

   SELECT cname,tname FROM course LEFT JOIN  teacher

   ON course.teacher_id =teacher.tid

2、查询学生表中男女生各有多少人? 如下:    
  SELECT gender,count(sid) 人数 FROM student GROUP BY gender
3、查询物理成绩等于100的学生的姓名?如下:
  SELECT sname from score left join student on score.student_id=student.sid
  where course_id=(select cid from course where cname='物理') and num=100
4、查询平均成绩大于八十分的同学的姓名和平均成绩,如下:
  SELECT sname,AVG(num) FROM student INNER JOIN score
                  
  ON student.sid=score.student_id
                  
  GROUP BY student_id HAVING AVG(num)>80

5、查询所有学生的学号,姓名,选课数,总成绩
  SELECT  sname,student.sid,COUNT(student.sid),SUM(num) FROM student
         
  INNER  JOIN score ON student.sid=score.student_id
         
  GROUP BY student_id

6、查询姓李老师的个数
  
  SELECT COUNT(tid) FROM teacher WHERE tname LIKE "李%"
   
7、查询没有报李平老师课的学生姓名   SELECT sname FROM student WHERE sid NOT IN
   
  (SELECT DISTINCT student_id FROM score WHERE course_id  IN
     
  (SELECT cid FROM teacher INNER JOIN course ON teacher.tid=course.teacher_id
                       
  WHERE tname LIKE "李平%"))

  8、查询物理课程比生物课程高的学生的学号   SELECT A.student_id,A.num,b.num FROM                
  (SELECT * FROM score WHERE course_id=(SELECT cid FROM course WHERE cname="物理"))as A    
  INNER JOIN    
  (SELECT * FROM score WHERE course_id=(SELECT cid FROM course WHERE cname="生物"))as B    
  ON A.student_id=B.student_id
  WHERE A.num>B.num

9、查询没有同时选修物理课程和体育课程的学生姓名
  SELECT sname FROM student WHERE sid NOT in (SELECT student_id FROM  score
     
  WHERE course_id in (SELECT cid FROM course WHERE cname="物理" OR cname="体育")
     
  GROUP BY student_id HAVING COUNT(sid)=2)

10、查询挂科超过两门(包括两门)的学生姓名和班级
  select sname,caption from student left join class on student.class_id=class.cid
  where sid in (select student_id from score where num<60 group by student_id having count(sid)>1)
11 、查询选修了所有课程的学生姓名
  select sname from score left join student on score.student_id=student.sid
  group by student_id
  having count(score.sid)=(select count(cid) from course)
  或者
  SELECT sname FROM student WHERE sid in (SELECT student_id FROM score
  GROUP BY student_id HAVING COUNT(sid)=(SELECT COUNT(cid) FROM course))

12、查询李平老师教的课程的所有成绩记录
  select * from score where course_id in (select cid from course
  left join teacher on course.teacher_id=teacher.tid
  where tname like '李平%')
13、查询全部学生都选修了的课程号和课程名
  select course_id,cname from score left join course on score.course_id=course.cid
  group by course_id
  having count(sid)=(select count(sid) from student )


14、查询每门课程被选修的次数
  select course_id,cname,count(sid)
  from score left join course on score.course_id=course.cid
  group by course_id


15、查询只选修了一门课程的学生姓名和学号
  select student_id,sname from score
  left join student on score.student_id=student.sid
  group by student_id having count(num)=1


16、查询所有学生考出的成绩并按从高到低排序(成绩去重)
  select distinct num from score order by num desc


17、查询平均成绩大于85的学生姓名和平均成绩
  select sname,avg(num) from score
  left join student on score.student_id=student.sid
  group by student_id
  having avg(num)>85


18、查询生物成绩不及格的学生姓名和对应生物分数
  select sname,num from score
  left join student on score.student_id=student.sid
  where course_id=(select cid from course where cname='生物') and num<60


19、查询在所有选修了李平老师课程的学生中,这些课程(李平老师的课程,不是所有课程)平均成绩最高的学生姓名
  select sname from score
  left join student on score.student_id=student.sid
  where course_id in (select cid from course
  left join teacher on course.teacher_id=teacher.tid
  where tname like '李平%')
  group by student_id
  order by avg(num) desc
  limit 1
  或者
  考虑不用limit用max函数写出来

20、查询每门课程成绩最好的前两名学生姓名

21、查询不同课程但成绩相同的学号,课程号,成绩

22、查询没学过“叶平”老师课程的学生姓名以及选修的课程名称;

23、查询所有选修了学号为1的同学选修过的一门或者多门课程的同学学号和姓名;

24、任课最多的老师中学生单科成绩最高的学生姓名

 关于关系表的创建:

# -----------------关于表的创建(一对一、一对多、多对多)------------------
# 书、作者、作者详细信息、出版社、书_作者
# 书--作者(多对多)  书--出版社(一对多)  作者--作者详细信息(一对一)
create table publish (
  id int primary key,
  name varchar(50),
  city varchar(50)
);

create table book (
  id int primary key,
  name varchar(50),
  price float(5,2),
  publish_id int not null,
  foreign key (publish_id) references publish (id)
);


create table author_info (
  id int primary key,
  city varchar(50),
  qq int
);

create table author (
  id int primary key,
  name varchar(50),
  author_id int not null,
  foreign key (author_id) references author_info (id)
);

create table book_author (
  id int primary key,
  book_id int not null,
  author_id int not null,
  foreign key (book_id) references book (id),
  foreign key (author_id) references author (id)
);

 

原文地址:https://www.cnblogs.com/metianzing/p/7242688.html