数据库系统以一些语句作为输入,并返回一些输出,例如sql查询总是返回一张表,我们定义:具有相同格式的记录的集合是一张表。

考虑大学数据库系统:

SQL中的数据类型:

char(n) 字符串长度为n  等价于 character

varchar(n) 可变字符串 最大长度n,等价于 character varing, 推荐都使用这种类型

int 整数 等价于 integer

smallint 小整数

numeric(p,d) 定点数,加上符号为共有p位数,其中d位数字在小数点右边,d表示精度

real 浮点数

double real 双精度浮点数

float(n)  浮点数,至少精度为n (float不精确,不能用于精确计算)

decimal(m,n) 表示数字。不仅仅是my sql,所有与精确数字有关的都不应该用float ,如价格、金额等

创建表:

create table department

  (dept_name varchar(20) not null,

  building varchar(15),

  budget numeric(12,2),

  primary key(dept_name, building));

create table course

  (course_id varchar(7) not null,

  title varchar(50),

  dept_name varchar(20),

  primary key (course_id),

  foreign key(dept_name) references department);

实际上,我们创建了一个关系模式,也创建了一个不包含记录的关系实例。

tips: 可以对一个属性添加not null约束,表示属性不能为空值。

create table course2 like course;

根据已有表创建新的空表,

create table course3 as

  (select *

  from course)

with data;

根据已有表创建新的表,并载入数据。

检索表:

select instrutor.*, department.dept_name

from instructor, department

where instructor.dept_name = department.dept_name and

  department.budget > 95000

order by instructor.salary desc, instructor.name asc;

我们知道笛卡尔积是这样一个函数(运算),接受多个集合作为参数,返回一个新的元组的集合,新集合的每个元组元素满足:元组中的各个元素分别属于各个参数集合。一张表是记录的集合,当然约束条件是每个记录都必须是相同结构的,多个记录的集合构成笛卡尔积,这个笛卡尔积也是一张表,从笛卡尔积中选择合适的元组组成一张表,最后从这张表中选择两个属性组成新的表,返回。语句执行顺序是 from -> where and -> group by -> select。

tips:where 子句可以用 and or not 连接谓词,也可以使用 between and 谓词

tips:desc 表示降序,asc表示如果salary相同按照name升序

tips:关系是记录的集合,所以不应该有重复项,但是SQL查询语句对应的返回值(也就是一张新的表)中默认有重复项,可以检查重复并且去除重复,但是这是很费时的。

select distinct dept_name

from instructor;

这表示返回的表中不能有重复

select all dept_name

from instructor;

显式地指明允许重复。

插入记录:

insert into instructor

  values(10211,'Smith','Biology',66000);

值被给出的顺序与关系模式中的属性顺序相同。

insert into student

  (select *

  from student_old);

更新记录:

update instructor

set salary = salary * 1.05

where salary < 7000;

删除记录:

delete from student;

这删除了全部的记录。

delete from student

where age < 20;

删除表:

drop table student;

改变属性:

alter table r

  add A D;

这是增添属性A,其中r是关系(表),A是属性名,D是属性的域。

alter table r

  drop A;

这是删除属性A。

自然连接:

select name, course_id

from  instructor natural join teaches natural join department;

连接(仅仅按照指定属性名称来匹配出记录元组):

select name, title

from (instructor natural join teaches) join course using (course_id);

别名:

select T.name as t_name

frome instructor as T

where T.salary > 8000;

as关键字用于创建一个新的引用,作为原来属性的别名。

模式匹配:

select dept_name

from department

where building like '_Waston\%_a%' escape '\' and building not like 'abc%';

tips: SQL中用单引号引用字符串,用双单引号''表示字符串内的双引号。可以用 escape定义转义字符。

tips: SQL1999中的 similar to 和like一样是模式匹配,语法类似unix中的正则表达式。

集合运算:

(select course_id from section

where year = 2010)

union all

(select course_id from section

where year = 2014);

all的含义是保留重复,否则默认删除重复记录,union, intersect, except用法相同。

基本聚集函数:

select avg(salary) as avg_salary

from instructor

where dept_name = 'Computer Science';

计算平均值,可以用distinct修饰一个属性表示去除重复

select count(distinct ID)

from teaches

where year = 2010;

计算年份在2010年的教学课程数目,可以计算总数

select count(*) from teaches;

分组聚集:

select dept_name, avg(salary) as avg_salary

from instructor

where age > 20

group by dept_name

having avg(salary) > 7000;

注意到,由group by 定义了多个分组,只能在分组内调用聚集函数,将一个集合映射称为一个值。

having关键字和where关键字后都跟一个谓词子句,然而区别是,where后的谓词作用于一个记录,having后的谓词作用于一个分组。也就是说,having后的子句必然包含有聚集函数。如果没有group by子句,则表示只有一个分组。

嵌套查询:

连接词 in 和 not in 可以检查元组(记录)是不是集合(表)中的成员。

select distinct course_id

from section

where year = 2010 and

  course_id in (select course_id

        from section

        where semester = 'Fall');

量词:some / all / exists

设集合为A,some(A)表示存在某个元素,all(A)表示任意一个元素。在用法上,可以把两者的返回值视为某条记录。

select name

from instructor

where salary > some(select salary

          from instructor

          where dept_name = 'Biology');

用all找出工资最高的系:

select dept_name

from instrutor

group by dept_name

having avg(salary) >= all(select avg(salary)

            from instructor

            group by dept_name);

exists(A)量词也表示存在,判定集合是否不为空集,返回布尔值。 not exists(A) 则判断A是否为空集。

如果不用联合查询,希望找到在不同学期同时开课的课程:

select course_id

from section as T

where year = 2011 and

   exists(select *

      from section as S

      where T.course_id = S.course_id and year = 2009);

select ID

from student as T

where exists(select *

      from takes as S

      where T.ID = S.student_id and

        S.course_id in (select course_id

                from course

                where dept_name = 'Biology');

max函数:

select dept_name, max(sum_salary)

from (select dept_name, sum(salary),

   from instructor

   group by dept_name) as dept_total(dept_name, sum_salary);

with子句:

它用于定义起到支持作用的关系模式。with 关系模式 as 关系实例,类似于程序语言中定义函数,用with子句避免了大量嵌套,使得SQL更有条理。注意它在定义的时候不执行

with sum_dept_salary(dept_name, sum_salary) as

  (select dept_name, sum(salary)

  from instructor

  group by dept_name),

  avg_sum_dept_salary(salary) as

  (select avg(sum_salary)

  from sum_dept_name)

select dept_name

from sum_dept_salary, avg_sum_dept_salary

where sum_dept_salary.sum_salary > avg_sum_dept_salary.salary;

选择结构case:

case

when pred1 then result1

when pred2 then result2

else result0

end

从case到end之间的部分可以作为一个整体子句,返回一个特定的值,可以嵌套在SQL中。

数据库语言(一):SQL语法实例整理的更多相关文章

  1. 数据库语言(二):SQL语法实例整理

    连接表达式: select * from student join takes on student.ID = takes.ID; 通过on后面的谓词作为连接条件,相同的属性可以出现两次,也就是等价于 ...

  2. 网络安全从入门到精通 (第二章-2) 后端基础SQL—MySQL数据库简介及SQL语法

    本文内容: 什么是数据库 常见数据库 数据库的基本知识 基本SQL语法 1,什么是数据库? 数据库就是将大量数据保存起来,通过计算机加工,可以高效访问的数据聚合. 数据库就是长期存储在计算机内,有组织 ...

  3. SQL语法粗整理

    1.在同一张表中,对前一条数据进行更新性插入操作,即:

  4. PHP实现把MySQL数据库导出为.sql文件实例(仿PHPMyadmin导出功能)

    1. 首先要得到该数据库中有哪些表,所用函数 mysql_list_tables(),然后可以将获取的所有表名存到一个数组.----------------该函数由于被弃用   用show table ...

  5. access 数据库创建表SQL语法

    create table R_CAIFA_B13 ( ID AUTOINCREMENT PRIMARY KEY, XB varchar(255), C1 varchar(50), C2 varchar ...

  6. 整理的一些数据库不容易想到的SQL语句实例一

    1.行转列SQL语句 SELECT * FROM ( SELECT [FID] , [Weeks] , [Qty] FROM dbo.TempTable where Weeks is not null ...

  7. 数据库SQL语法到MySQL实操

    一.基础 1.说明:创建数据库CREATE DATABASE database-name 2.说明:删除数据库drop database dbname 3.说明:备份sql server--- 创建 ...

  8. NoSQL 数据库概览及其与 SQL 语法的比较

    NoSQL数据库的产生就是为了解决大规模数据集合多重数据种类带来的挑战,尤其是大数据应用的难题. 本文对NoSQL数据库的定义.分类.特征.当前比较流行的NoSQL数据库系统等进行了简单的介绍,并对N ...

  9. Oracle数据库常用的Sql语句整理

    Oracle数据库常用的Sql语句整理 查看当前用户的缺省表空间 : select username,default_tablespace from user_users; 2.查看用户下所有的表 : ...

随机推荐

  1. ssh连接慢

    suse刚装完,开始用ssh的时候,总会遇到这样的问题:输入了用户名以后,等半天才出输入密码的框,很是急人.这是dns反查造成的.解决方法:编辑 /etc/ssh/sshd_conf , 将 #Use ...

  2. 翻译:AngularJS应用的认证技术

    原文: https://medium.com/opinionated-angularjs/7bbf0346acec 认证 最常用的表单认证就是用户名(或者邮件)和密码登录.这就表示要实现一个用户可以输 ...

  3. UVA 11424 GCD - Extreme (I) (欧拉函数+筛法)

    题目:给出n,求gcd(1,2)+gcd(1,3)+gcd(2,3)+gcd(1,4)+gcd(2,4)+gcd(3,4)+...+gcd(1,n)+gcd(2,n)+...+gcd(n-1,n) 此 ...

  4. [SQL Server 系] -- 模糊查询

    SQL Server中的通配符有下面四种 通配符 说明 % 包含零个或多个字符的任意字符串 _(下划线) 任意单个字符 [ ] 任意在指定范围或集合中的单个字符 [^ ] 任意不在指定范围或集合中的单 ...

  5. Java Socket文件上传

    客户端: import java.io.FileInputStream; import java.net.Socket; /** * Created by 290248126 on 14-5-11. ...

  6. Gulp实战和原理解析

    Gulp实战和原理解析(以weui作为项目实例)http://i5ting.github.io/stuq-gulp/

  7. CAS(Compare and Swap)理解

    什么叫CAS(Compare and Swap)?  硬件同步原语!! 什么蛋疼的名字,一般人很难理解.根据英文全称翻译==比较与交换,这个名字大致还能理解一点,目前先暂且这么理解吧. 有啥用处? 对 ...

  8. eclipse的设置和优化

    转载:http://my.oschina.net/zhaoqian/blog/66545 1.eclipse下的编码设置: eclipse 中使用模板新建 JSP,xhtml等 文件时,默认的编码为: ...

  9. 输出进程相关联的环境变量信息(使用GetEnvironmentStrings取得信息,然后使用StringCchCopyN和StringCchPrintf保证字符串不会越界)

    void DumpEnvironmentStrings() { #define MAX_ENVIRONMENT_NAME_LENGTH     (128) #define MAX_ENVIRONMEN ...

  10. 转Java 回调函数的理解

    所谓回调,就是客户程序C调用服务程序S中的某个函数A,然后S又在某个时候反过来调用C中的某个函数B,对于C来说,这个B便叫做回调函数.例如Win32下的窗口过程函数就是一个典型的回调函数.一般说来,C ...