@linux1s1s
2018-02-08T14:28:13.000000Z
字数 2029
阅读 1197
Big-Data-Base
2018-02
# 创建数据库STUDENT
CREATE DATABASE STUDENT;
# 创建表STUDENT
CREATE TABLE STUDENT
(SNO VARCHAR(3) NOT NULL,
SNAME VARCHAR(4) NOT NULL,
SSEX VARCHAR(2) NOT NULL,
SBIRTHDAY DATETIME,
CLASS VARCHAR(5));
# 创建表COURSE
CREATE TABLE COURSE
(CNO VARCHAR(5) NOT NULL,
CNAME VARCHAR(10) NOT NULL,
TNO VARCHAR(10) NOT NULL);
# 创建表SCORE
CREATE TABLE SCORE
(SNO VARCHAR(3) NOT NULL,
CNO VARCHAR(5) NOT NULL,
DEGREE NUMERIC(10, 1) NOT NULL);
# 向各表导入数据
INSERT INTO STUDENT (SNO,SNAME,SSEX,SBIRTHDAY,CLASS) VALUES
(108 ,'曾华' ,'男' ,'1977-09-01',95033),
(105 ,'匡明' ,'男' ,'1975-10-02',95031),
(107 ,'王丽' ,'女' ,'1976-01-23',95033),
(101 ,'李军' ,'男' ,'1976-02-20',95033),
(109 ,'王芳' ,'女' ,'1975-02-10',95031),
(103 ,'陆君' ,'男' ,'1974-06-03',95031);
(102 ,'汪洋' ,'男' ,'1975-06-03',95032);
INSERT INTO COURSE(CNO,CNAME,TNO) VALUES
('3-105' ,'计算机导论',825),
('3-245' ,'操作系统' ,804),
('6-166' ,'数据电路' ,856),
('9-888' ,'高等数学' ,100);
INSERT INTO SCORE(SNO,CNO,DEGREE) VALUES
(103,'3-245',86),
(105,'3-245',75),
(109,'3-245',68),
(103,'3-105',92),
(105,'3-105',88),
(109,'3-105',76),
(101,'3-105',64),
经过以上简单的数据准备(以上数据会有部分修改,所以和下面展现的表格不一样,但是字段一致),分别有三个表格,
score
,student
,course
,现将数据表展现如下:
如何解决上面的问题,一个思路应该是将三张表联系起来,很明显应该将上面的三个表格关联起来,我们看一下不同关联下的数据如何.
join
join与inner join对比
left join 与 right join 对比
上面不同的关联方式,可以参看下面列举的参考文章, 上面提及的问题,用join或innerjoin on xxx
比较合适,然后再加上相应的条件即可.
select score.* from score join(student, course) on score.sno=student.sno and score.cno=course.cno where student.ssex='男' and course.cname='计算机导论';
如果觉得上面太长,可以将表名称用简写作为别名,比如
select A.* from score A join(student B, course C) on A.sno=B.sno and A.cno=C.cno where B.ssex='男' and C.cname='计算机导论';
结果:
+-----+-------+--------+
| sno | cno | degree |
+-----+-------+--------+
| 105 | 3-245 | 75.0 |
+-----+-------+--------+
1 row in set (0.00 sec)
select A.* from score A inner join (select cno, AVG(degree) C from score group by cno) B on A.cno=B.cno where degree<C
上面
- A 是score表的别名,
- C 是 degree的别名,作为表B的列名称
- B 是 以cno 和 C 为列名的表, A表和B表以cno列名为关联结果:
+-----+-------+--------+
| sno | cno | degree |
+-----+-------+--------+
| 105 | 3-245 | 75.0 |
| 106 | 3-105 | 86.0 |
| 109 | 3-166 | 69.0 |
+-----+-------+--------+
3 rows in set (0.01 sec)