关系数据库SQL之基本数据查询:子查询、分组查询、模糊查询
http://www.jianshu.com/p/eeb6a898d4ec
前言
上一篇关系数据库常用SQL语句语法大全主要是关系型数据库大体结构,本文细说一下关系型数据库查询的SQL语法。
语法回顾
SELECT [ALL|DISTINCT] <目标列表达式>[,<目标列表达式>]…
FROM <表名或视图名>[,<表名或视图名>]…
[WHERE <条件表达式>]
[GROUP BY <列名> [HAVING <条件表达式>]]
[ORDER BY <列名> [ASC|DESC]…]
SQL查询语句的顺序:SELECT、FROM、WHERE、GROUP BY、HAVING、ORDER BY。SELECT、FROM是必须的,HAVING子句只能与GROUP BY搭配使用。
准备工作
1.创建数据库和数据表
2.插入基本数据
3.本文以SQL Server为例介绍
-- 创建学生表
CREATE TABLE Students(
Id int NOT NULL PRIMARY KEY,
Name varchar(20) NOT NULL,
Class varchar(15) NOT NULL,
Gender varchar(10) NULL,
Age int NULL,
Phone varchar(15) NULL,
[Address] varchar(100) NULL
)
-- 创建课程表
CREATE TABLE Courses(
Id int NOT NULL PRIMARY KEY IDENTITY(1,1),
Name varchar(50) NOT NULL
);
-- 创建成绩表
CREATE TABLE Scores(
Id int PRIMARY KEY IDENTITY(1,1),
SId int NOT NULL,
CId int NOT NULL,
Grades decimal(5,2) NOT NULL,
IsPassed bit NOT NULL
);
-- 插入学生表基础数据
INSERT INTO Students (Id,Name,Class,Gender,Age,Phone,[Address]) VALUES(2016001,'小明','一班','男',20,'18817716611','北京');
INSERT INTO Students (Id,Name,Class,Gender,Age,Phone,[Address]) VALUES(2016002,'小龙','一班','男',19,'18817716622','天津');
INSERT INTO Students (Id,Name,Class,Gender,Age,Phone,[Address]) VALUES(2016003,'小王','二班','男',20,'18817716633','北京');
INSERT INTO Students (Id,Name,Class,Gender,Age,Phone,[Address]) VALUES(2016004,'婷婷','一班','女',17,'18817716644','济南');
INSERT INTO Students (Id,Name,Class,Gender,Age,Phone,[Address]) VALUES(2016005,'张三','一班','男',19,'18817716655','北京');
INSERT INTO Students (Id,Name,Class,Gender,Age,Phone,[Address]) VALUES(2016006,'小赵','一班','男',20,'18817716666','北京');
INSERT INTO Students (Id,Name,Class,Gender,Age,Phone,[Address]) VALUES(2016007,'丽丽','二班','女',18,'18817716677','北京');
INSERT INTO Students (Id,Name,Class,Gender,Age,Phone,[Address]) VALUES(2016008,'花花','一班','女',19,'18817716688','沈阳');
INSERT INTO Students (Id,Name,Class,Gender,Age,Phone,[Address]) VALUES(2016009,'静静','二班','女',20,'18817716699','北京');
-- 插入课程表基础数据
INSERT INTO Courses(Name) VALUES('语文');
INSERT INTO Courses(Name) VALUES('数学');
INSERT INTO Courses(Name) VALUES('英语');
-- 插入成绩表基础数据
INSERT INTO Scores(SId,CId,Grades,IsPassed) VALUES(2016001,1,120,1);
INSERT INTO Scores(SId,CId,Grades,IsPassed) VALUES(2016001,2,70,0);
INSERT INTO Scores(SId,CId,Grades,IsPassed) VALUES(2016001,3,89,