【完结✅】SQL基础知识复习

SQL快速参考:https://www.runoob.com/sql/sql-quickref.html

select * from Websites;     //选择Websites表中的所有数据

Select name, country from websites;    //选择websites表中的name列和country列数据

Select distinct country from websites;      //选择websites表中country列的唯一值,也就是去掉country列中的重复值

select * from websites where country=‘CN’;    //选择websites表中country列的值等于CN的所有数据。文本字段使用单引号,数值字段不用引导。

Selcet * from websites where id=1;    //选择websites表中id列的值为1的所有数据。

where 子句中的运算符可使用

= 等于

<> 不等于,或者!=

> 大于

< 小于

>= 大于等于

<= 小于等于

between 在某个范围内

like 搜索某种模式,模糊查询

in 指定针对某个列的多个可能值

and 如果条件一和条件二都成立,则显示一条记录

or 如果条件一和条件二只要有一个成立,则显示一条记录

and和or也可以结合,形成更复杂的表达式

select * from websites where country =‘CN’ and alexa>50;    //选择websites表中country列的值为CN,并且alexa列的值大于50的所有数据

select * from websites where country=‘CN’ or alexa>50;    //选择websites表中country列的值为CN,或者alexa列的值大于50的所有数据

selcet * from websites where alexa>15 and (country=‘CN’ or country=‘USA’);    //选择websites表中Alexa列的值大于15,并且country列的值为CN或USA的所有数据

order by 用于对结果集按照一列或多列进行排序,默认按照升序对记录进行排序,如果需要按照降序对记录进行排序,可以使用desc

select * from websites order by alexa;    //选择Websites表中的所有数据,结果集根据alexa列中的数据正序排序

selcet * from websites order by alexa desc;    //选择websites表中的所有数据,结果集根据alexa列中的数据倒序排列

selcet * from websites order by country,alexa;    //选择websites表中的所有数据,结果集依次根据country列中的数据、alexa列中的数据正序排序

insert into 向表中插入新纪录。有2种编写形式,一是无需指定要插入的数据的列名,只需提供被插入的值即可,二是需要指定列名及被插入的值。

Insert into websites (name,url,alexa,country)values (‘百度’,’www.baidu.com’,’10’,’CN’);    //在websites表中插入一行新数据,name列,url列,alexa列,country列的值分别为百度,www.baidu.com,10,CN

//表中的id字段无需插入内容,id列是自动更新的,表中的每条记录都有一个唯一的数字

Insert into websites (name,url,country)values (’微梦’,’xmm1995sunshine.xyz’,’CN’);    //在websites表中的指定列插入一行新数据,name列,url列,country列的值分别为微梦,xmm1995sunshine.xyz,CN

update 用于更新表中已存在的记录。注意update一定要搭配where子句,where子句规定哪些记录需要更新,如果省略,所有记录将被更新!执行没有where子句的update务必慎重!!!

update websites set alexa=‘5000’,country=‘USA’ where name='菜鸟教程’; //把 "菜鸟教程" 的 alexa 排名更新为 5000,country 改为 USA

delete 用于删除表中的行。注意delete一定搭配where子句,where子句规定哪些记录需要删除,如果省略,所有记录将被删除!

delete from websites where name=‘脸书’ and country=‘USA’;    //从 "Websites" 表中删除网站名为 “脸书" 且国家为 USA 的网站

//以下2句可在不删除表的情况下,删除表中所有行,这意味着表结构、属性、索引将保持不变。在删除时务必格外小心!因为不能重来!

delete from table_name;

delete * from table_name;

Select * from websites limit 2;    //选择websites表中前2行的数据。MySQL SELECT LIMIT 实例

Select top 50 percent * from websites;    //选择websites表中前50%的数据。在 Microsoft SQL Server 中还可以使用百分比作为参数。

lile 用于在where子句中搜索列中的指定模式。

Select * from websites where name like ‘G%’;    //选择websites表中name以“G”开始的所有数据。“%”符号用于在模式的前后定义通配符(默认字母)。

Select * from websites where name like '%k';//选择websites表中name以“k”结尾的所有数据。

Select * from websites where name like '%oo%';//选择websites表中name包含“oo”的所有数据。

Select * from websites where name not like '%oo%';//选择websites表中name不包含“oo”的所有数据。

通配符 可用于替代字符串中的任何其他字符。

通配符和lile操作符一起使用。

%    //替代0个或多个字符

_      //替代一个字符

[charlist]    //字符列中的任何单一字符

[^charlist]或[!charlist]    //不在字符列中的任何单一字符

Select * from websites where url like 'https%';    //选择websites表中url以https开头的所有网站

Select * from websites where url like '%oo%';    //选择websites表中url包含oo的所有网站

Select * from websites where name like '_oogle’;    选择websites表中name以任一字符开始,然后后面是oogle的所有数据

Select * from websites where name like ‘G_o_le';    //选取 name 以 "G" 开始,然后是一个任意字符,然后是 "o",然后是一个任意字符,然后是 "le" 的所有网站:

Select * from websites where name regexp ‘^[GFs]';    //选取name以G、F、s开始的所有网站

Select * from websites where name regexp '^[A-H]';    //选取 name 以 A 到 H 字母开头的网站

Select * from websites where name regexp ‘^[^A-H]';    //选取 name 不以 A 到 H 字母开头的网站

in 操作符可以在where子句中规定多个值

Select * from websites where name in ('Google',’阿里云');//选取name为Google或阿里云的所有数据 

Between 操作符用于选取介于两个值之间的数据范围的值,值包含数值、文本、日期。

【数值选取】

Select * from websites where alexa between 1 and 20;    //选取 alexa 介于 1 和 20 之间的所有网站

Select * from websites where alexa not between 1 and 20;    //选取 alexa 不在 1 和 20 之间的所有网站

Select * from websites where (alexa between 1 and 20) and country not in(‘USA’,'IND’);    //选取 alexa 介于 1 和 20 之间但 country 不为 USA 和 IND 的所有网站

【文本值选取】

Select * from websites where name between ‘A' and ‘H’;    //选取name以介于A和H之间字母开始的所有网站

Select * from websites where name not between ‘A' and ‘H’;    //选取name不介于A和H之间字母开始的所有网站

【日期选取】

Select * from access_log where date between '2016-05-10’ and '2016-05-14’;     //选取 date 介于 '2016-05-10' 和 '2016-05-14' 之间的所有访问记录

请注意,在不同的数据库中,BETWEEN 操作符会产生不同的结果!

在某些数据库中,BETWEEN 选取介于两个值之间但不包括两个测试值的字段。

在某些数据库中,BETWEEN 选取介于两个值之间且包括两个测试值的字段。

在某些数据库中,BETWEEN 选取介于两个值之间且包括第一个测试值但不包括最后一个测试值的字段。

因此,请检查您的数据库是如何处理 BETWEEN 操作符!

as 别名,可以为表名称或列名称指定别名。

Select name as n , country as c  from websites;     //name 列的别名n,country 列的别名c。提示:如果列名称包含空格,要求使用双引号或方括号

Select name,concat(url,’,’,alexa,’,’,country) as site_info from websites;    //把三个列(url、alexa 和 country)结合在一起,并创建一个名为 "site_info" 的别名

Select w.name,w.url,a.count,a.date from websites as w,access_log as a where a.site_id=w.id and w.name=“菜鸟教程”;    //选取 "菜鸟教程" 的所有访问记录。我们使用 "Websites" 和 "access_log" 表,并分别为它们指定表别名 "w" 和 "a"(通过使用别名让 SQL 更简短)

Join 连接,用于把两个或多个表的行结合起来

下图展示了 LEFT JOIN、RIGHT JOIN、INNER JOIN、OUTER JOIN 相关的 7 种用法

Inner join:如果表中至少有一个匹配,则返回行;

Left join:即使右表没有匹配,也从左表返回所有行;

Right join:即使左表没有匹配,也从右表返回所有行;

Full join:只要其中一个表存在匹配,则返回行。

Inner join和join是相同的,都是关键词在表中存在至少一个匹配时返回行。

最常见的join类型:inner join,从多个表中返回满足JOIN条件的所有行。

Select websites.id,websites.name,access_log.count,access_log.date

From websites

Inner join access_log

On websites.id=access_log.site_id

Order by access_log.count;

//使用inner join将websites和access_log表关联,并返回两表都包含的数据。

//如果websites表中的行在access_log中没有匹配,则不会列出这些行。

//join语句后经常使用on、where语句,先on,再where

 Websites 作为左表,access_log 作为右表。

Left join 关键词从左表(table1)返回所有的行,即使右表(table2)中没有匹配。如果右表中没有匹配,则结果为NULL。

Left join 也可称为left outer join

Select websites.name,access_log.count,access_log.date

From websites

Left join access_log

On websites.id=access_log.site_id

Order by access_log.count desc;

Right join 关键字从右表(table2)返回所有的行,即使左表(table1)中没有匹配。如果左表中没有匹配,则结果为 NULL。

Right join 也可称为right outer join

Select websites.name,access_log.count,access_log.date

From websites

Right join access_log

On access_log.site_id=websites.id

Order by access_log.count desc;

Full outer join 关键字只要左表(table1)和右表(table2)其中一个表中存在匹配,则返回行。

FULL OUTER JOIN 关键字返回左表(Websites)和右表(access_log)中所有的行。如果 "Websites" 表中的行在 "access_log" 中没有匹配或者 "access_log" 表中的行在 "Websites" 表中没有匹配,也会列出这些行。

Full outer join 关键字结合了left join 和right join的结果。

Mysql 中不支持full outer join,可在sql server中测试以下实例。

Select websites.name,access_log.count,access_log.date

From websites

Full outer join access_log

On websites.id=access_log.site_id

Order by access_log.count desc;

Union 操作符合并两个或多个select语句的结果。需注意,每个select 语句必须拥有相同数量的列,列也必须拥有相似的数据类型,且每个select语句中的列顺序必须相同。

Union 操作符默认选取不同的值,如果允许重复的话,需使用union all,列名默认选择第一个select语句中的列明。

从 "Websites" 和 "apps" 表中选取所有不同的country(只有不同的值)

Select country from websites

Union

Select country from apps

Order by country;

从 "Websites" 和 "apps" 表中选取所有的country(也有重复的值)

Select country from websites

Union all

Select country from apps

Order by country;

从 "Websites" 和 "apps" 表中选取所有的中国(CN)的数据(也有重复的值)

Select country,name from websites where country=‘CN'

Union all

Select country,app_name from apps Where country = ‘CN'

Order by country;

Select into 把一个表的信息复制到另一个新表中

mysql 数据库不支持select…into语句,但支持insert into…select

也可用如下语句复制表结构及数据

Create table 新表名

As

Select * from 旧表名

复制所有列插入到新表中:

Select * into newtable from table;

只复制希望的列插入到新表中:

Select column_name as new_col_name

into newtable

from table;

-创建 Websites 的备份复件:

Select *

into websitesbackup2022

From websites

-只复制一些列插入到新表中:

Select name, url

Into websitesbackup2022

From websites;

-只复制中国的网站插入到新表中:

Select * 

Into websitesbackup2022

From websites

Where country=‘CN';

-复制多个表中的数据插入到新表中:

Select websites.name,access_log.count,access_log.date

Into websitesbackup2022

From websites left join access_log

On websites.id=access_log.site_id;

SELECT INTO 语句可用于通过另一种模式创建一个新的空表。只需要添加促使查询没有数据返回的 WHERE 子句即可:

select *

into new_websites

from websites

Where 1=0;

从一个表中复制所有的列插入到另一个已存在的表中:

Insert into table2 select * from table1;

只复制指定列插入到另一个已存在的表中:

Insert into table(name,url) select name, url from table1;

复制 "apps" 中的数据插入到 "Websites" 中:

Insert into websites(name,country) 

select app_name,country from apps;

只复 id=1 的数据到 "Websites" 中:

Insert into websites(name,country) 

select app_name,country from apps 

where id=1;

Select...into from和insert into...select都用来复制表

区别在于select…into from要求目标表不存在,因为插入时会自动创建。【可复制表结构和数据】

思路:查询出结果->复制一张同结构的表->把数据复制进表

Insert into…select from要求目标表存在。【只能复制数据】

思路:先看想要插入的表2结构->在表1中筛选数据->严格按照表1结构插入数据。

1、复制表结构及数据

select * into table2 from table1;

Create table websites as select * from table1;

2、只复制表结构

Select * into table2 from table1 where 1=0;

Create table websites as select * from table1 where 1=2;

Create table websites like table1;

3、只复制表数据

如果表结构一样

Insert into table2 select * from table1;

如果表结构不一样,只选取相同的部分

Insert into table2(name,country) select name,country from table2;

Create database dynamo;    //创建数据库

create table table_name

(

Column_name1 data_type(size),

Column_name2 data_type(size),

…...

);

//创建数据库中的表

//Column_name 列的名称

//data_type列的数据类型(如varchar、integer、decimal、date 等等)

//size参数规定表中列的最大长度

创建一个名为 "Persons" 的表,包含五列:PersonID、LastName、FirstName、Address 和 City。

PersonID 列的数据类型是 int,包含整数。

LastName、FirstName、Address 和 City 列的数据类型是 varchar,包含字符,且这些字段的最大长度为 255 个字符。

Create table persons

(

personID int,

Lastname varchar(255),

Firstname varcher(255),

Address varcher(255),

City varcher(255)

);

可使用insert into 在表中插入数据:

Insert into persons(personID,Lastname,Firstname,Address,City) values (1,'miki’,'xue’,'changping’,'beijing');

约束(constraints)用于规定表中的数据规则。如果存在违反约束的数据行为,行为会被约束终止。

约束可以在创建表时规定(通过 CREATE TABLE 语句),或者在表创建之后规定(通过 ALTER TABLE 语句)。

create table+constraints语法

Create table table_name

(

Column_name1 date_type(size) constraints_name,

Column_name2 date_type(size) constraints_name,

Column_name3 date_type(size) constraints_name

);

//constraints_name约束类型

约束有如下几种:

not null -指定列的值不能为空。

unique -指定列的值必须唯一,不能重复。

primary key -与not null和unique结合使用,确保某列(或两个列多个列的结合)有唯一标识,有助于更容易更快速地找到表中的一个特定的记录。

foreign key -参照此列的值匹配另一个表的值。

check -保证列中的值符合指定的条件。

default -规定没有给列赋值时的默认值。

Not null    默认情况下,表的列接受null值,如果加上not null约束强制列不接受null值。

这意味着如果不向字段添加值,就无法插入新纪录或者更新记录。

强制 "ID" 列、 "LastName" 列以及 "FirstName" 列不接受 NULL 值:

Create table persons(

ID int not null,

Lastname varchar(255) not null,

Firstname varchar(255) not null,

Age int

);

在已创建的persons表age字段null约束改为not null:

alter table Persons modify age int not null;

not null约束改为null:

Alter table Persons modify age int null;

Unique 约束为列或列集合提供了唯一性的保证,同primary key。

不同的是,每个表可以有多个unique约束,但是每个表只能有一个primary key约束。

在 创建"Persons" 表时,在 "P_Id" 列上创建 UNIQUE 约束:

【MySQL】

Create table Persons(

P_id int not null,

Lastname varchar(255) not null,

Firstname varchar(255),

Address varchar(255),

City varchar(255),

Unique (P_id)

)

【SQL Server / Oracle / MS Access】

Create table Persons(

P_id int not null unique,

Lastname varchar(255) not null,

Firstname varchar(255),

Address varchar(255),

City varchar(255)

)

【MySQL / SQL Server / Oracle / MS Access】定义多个列的unique约束

Create table Persons(

P_id int not null,

Lastname varchar(255) not null,

Firstname varchar(255),

Address varchar(255),

City varchar(255),

Constraint uc_PersonID unique (P_id,Lastname)

)

当表已被创建时,如需在 "P_Id" 列创建 UNIQUE 约束:

【MySQL / SQL Server / Oracle / MS Access】

alter table Persons add unique (P_id)

当表已被创建时,定义多个列的unique约束:

【MySQL / SQL Server / Oracle / MS Access】定义多个列的约束

Alter table Persons add constraint uc_PersonID unique (P_id,Lastname)

撤销unique约束

【MySQL】

Alter table persons drop index uc_personID

【SQL Server / Oracle / MS Access】

Alter table persons drop constraint uc_PersonID

alter 改变;(使)更改

modify 修改

add 增加

drop 停止;撤销

constraint 限制;限定;约束

Primary key 约束唯一标识数据库表中的每条记录。

主键必须包含唯一的值,主键列不能包含null值。每个表都应该有一个主键,且每个表只能有一个主键。

【MySQL】

Crate table persons(

P_id int not null,

Lastname varchar(255) not null,

Firstname varchar(255),

Address varchar(255),

City varchar(255),

Primary key (P_id)

)

【SQL Server / Oracle / MS Access】

Crate table persons(

P_id int not null primary key,

Lastname varchar(255) not null,

Firstname varchar(255),

Address varchar(255),

City varchar(255)

)

【MySQL / SQL Server / Oracle / MS Access】定义多个列的primary key约束

Crate table persons(

P_id int not null,

Lastname varchar(255) not null,

Firstname varchar(255),

Address varchar(255),

City varchar(255),

Constraint  pk_PersonID primary key (P_id,Lastname)

)

上面这一多列primary key约束实例中,主键只有一个pk_PersonID,该主键由两列(P_id,Lastname)组成,这2列必须是not null。

当表已被创建时,如需在 "P_Id" 列创建 PRIMARY KEY 约束:

【MySQL / SQL Server / Oracle / MS Access】

alter table Persons add primary key (P_id)

当表已被创建时,定义多个列的PRIMARY KEY约束:

【MySQL / SQL Server / Oracle / MS Access】定义多个列的约束

Alter table Persons add constraint pk_PersonID primary key (P_id,Lastname)

被设置为primary key约束的2列,必须确保首次创建时不包含null值。

撤销primary key约束

【MySQL】

Alter table persons drop primary key

【SQL Server / Oracle / MS Access】

Alter table persons drop constraint pk_PersonID

references 涉及;提到;查询;参考

Foreign key 一个表中的foreign key指向另一个表的unique key(唯一约束的键)

在 "Orders" 表创建时在 "P_Id" 列上创建 FOREIGN KEY 约束:

【MySQL】

Create table orders(

O_id int not null,

OrderNo int not null,

P_id int,

Primary key (O_id),

Foreign key (P_id) references Persons(P_id)

)

【SQL Server / Oracle / MS Access】

Create table orders(

O_id int not null primary key,

OrderNo int not null,

P_id int foreign key references Persons(P_id)

)

【MySQL / SQL Server / Oracle / MS Access】定义多个列的foreign key约束

Create table orders(

O_id int not null,

OrderNo int not null,

P_id int,

Primary key (O_id),

constraint fk_PerOrders foreign key (P_id) references Persons(P_id)

)

当表已被创建时,如需在 "P_Id" 列创建 FOREIGN KEY 约束:

【MySQL / SQL Server / Oracle / MS Access】

alter table Orders add foreign key (P_id) references Persons(P_id)

当表已被创建时,定义多个列的 FOREIGN KEY 约束:

【MySQL / SQL Server / Oracle / MS Access】定义多个列的约束

Alter table Ordersadd constraint fk_PerOrders foreign key Persons(P_id)

撤销foreign key约束

【MySQL】

Alter table Orders drop foreign key fk_PerOrders

【SQL Server / Oracle / MS Access】

Alter table Orders drop constraint fk_PerOrders

Check 约束用于限制列中值的范围。

如果对单个列定义 CHECK 约束,那么该列只允许特定的值。

如果对一个表定义 CHECK 约束,那么此约束会基于行中其他列的值在特定的列中对值进行限制。

在 "Persons" 表创建时在 "P_Id" 列上创建 CHECK 约束。CHECK 约束规定 "P_Id" 列必须只包含大于 0 的整数。

【MySQL】

create table Persons(

P_id int not null,

Lastname varchar(255) not null,

Firstname varchar(255),

Adress varchar(255),

City varchar(255),

Check (P_id>0)

)

【SQL Server / Oracle / MS Access】

create table Persons(

P_id int not null check (P_id>0),

Lastname varchar(255) not null,

Firstname varchar(255),

Adress varchar(255),

City varchar(255)

)

【MySQL / SQL Server / Oracle / MS Access】定义多个列的check约束

create table Persons(

P_id int not null,

Lastname varchar(255) not null,

Firstname varchar(255),

Adress varchar(255),

City varchar(255),

Constraint chk_Person check (P_id>0 and city=‘Beijing')

)

当表已被创建时,如需在 "P_Id" 列创建 check 约束:

【MySQL / SQL Server / Oracle / MS Access】

alter table Persons add check (P_id>0)

当表已被创建时,定义多个列的 check 约束:

【MySQL / SQL Server / Oracle / MS Access】定义多个列的约束

Alter table Persons add constraint chk_Person check (P_id>0 and city=‘Beijing')

撤销check约束

【MySQL】

Alter table Persons drop check chk_Person

【SQL Server / Oracle / MS Access】

Alter table Orders drop constraint chk_Person

default 默认;系统设定值;预置值

date 日期

data 数据

Default 约束用于向列插入默认值。如果没有规定其他的值,那么会将默认值添加到所有的新纪录。

 在 "Persons" 表创建时在 "City" 列上创建 DEFAULT 约束:

create table Persons(

P_id int not null,

Lastname varchar(255) not null,

Firstname varchar(255),

Adress varchar(255),

City varchar(255) default ‘Beijing'

)

通过使用类似 GETDATE() 这样的函数,DEFAULT 约束也可以用于插入系统值:

Create table Orders(

O_id int not null,

OrderNo int not null,

P_id int,

OrderDate date default getdate()

)

当表已被创建时,如需在 "City" 列创建 DEFAULT 约束:

【MySQL】

Alter table Persons alter City set default ‘Beijing'

【SQL Server / MS Access】

Alter table Persons add constraint ab_c default ‘beijing’ for city 

【Oracle】

Alter table Persons modify city default ‘beijing’

撤销default约束

【MySQL】

Alter table Persons alter city drop default

【SQL Server / Oracle / MS Access】

Alter table Persons alter column city default

Create indes 语句用于在表中创建索引。在不读取整个表的情况下,索引使数据库应用程序可以更快地查找数据。

用户无法看到索引,它们只能被用来加速搜索/查询。

注释:更新一个包含索引的表需要比更新一个没有索引的表花费更多的时间,这是由于索引本身也需要更新。因此,理想的做法是仅仅在常常被搜索的列(以及表)上面创建索引。

用于创建索引的语法在不同的数据库中不一样。因此,检查您的数据库中创建索引的语法。

在 "Persons" 表的 "LastName" 列上创建一个名为 "Per_Index" 的索引:

Create index Per_Index on Persons (Lastname)

如索引不止一个列,可以在括号中列出这些列的名称,用逗号隔开:

Create index Per_Index on Persons (Lastname,Firstname)

在表上创建唯一索引,不允许使用重复值:

Create unique index Per_Index on Persons (Lastname)

drop语句,可删除索引、表、数据库。 

撤销索引

【MySQL】

Alter table Persons drop index Per_Index 

【MS SQL Server】

Drop index Persons.Per_Index

【DB2/Oracle】

Drop index Per_Index

【MS Access】

Drop index Per_Index on Per_Index

撤销表

Drop table Persons

撤销数据库

Drop database CAINIAO

删除表内数据,不删除表本身

Truncate table Persons

truncate 截短;删节(尤指掐头或去尾)

Alter table 语句用于在已有的表中添加、删除、修改列。

在Persons表中增加DateOfBirth列:

Alter table Persons add DateOfBirth date    //date 表示数据类型是日期,可以存放日期。

改变表中列的数据类型:

【SQL Server/MS Access】

Alter table Persons alter columnDateOfBirth year    //year 数据类型是年,可以存放2位或4位格式的年份

【MySQL/Oracle】

Alter table Persons modify columnDateOfBirth year

【Oracle 10G之后版本】

Alter table Persons modify DateOfBirth year

删除表中的DateOfBirth列:

Alter table Persons drop columnDateOfBirth

identity 身份;本体;特征

Auto increment 会在新纪录插入表中时生成一个唯一的数字,可以作为主键字段的值。

把 "Persons" 表中的 "ID" 列定义为 auto-increment 主键字段:

【MySQL】

Create table Persons(

ID int not null auto increment,    //MySQL使用auto_increment关键字来执行自增任务。默认开始值为1,每条新增记录递增1

Lastname varchar(255) not null,

Firstname varchar(255),

Adress varchar(255),

City varchar(255),

Primary key (ID)

)

使用其他值起始递增:

Alter table Persons auto_increment=100

要在 "Persons" 表中插入新记录,我们不必为 "ID" 列规定值(会自动添加一个唯一的值):

Insert into Persons (Firstname,Lastname) values (‘Miki’,’xue’)

【SQL Server】

Create table Persons(

ID int identity(1,1) primary key,    //SQL Server使用identity关键字来执行自增任务。identity开始值是1,每条新纪录递增1

Lastname varchar(255) not null,

Firstname varchar(255),

Adress varchar(255),

City varchar(255)

)

提示:要规定 "ID" 列以 10 起始且递增 5,请把 identity 改为 IDENTITY(10,5)。

【Access】

Create table Persons(

ID integer primary key autoincrement,    //Access使用autoincrement关键字来执行自增任务。默认开始值是1,每条新纪录递增1

Lastname varchar(255) not null,

Firstname varchar(255),

Adress varchar(255),

City varchar(255)

)

提示:要规定 "ID" 列以 10 起始且递增 5,请把 autoincrement 改为 AUTOINCREMENT(10,5)。

【Oracle】必须通过 sequence对象(该对象生成数字序列)创建auto-increment字段

Create sequence seq_person

minvalue 1

start with 1

increment by 1

cache 10

上面的代码创建一个名为 seq_person 的 sequence 对象,它以 1 起始且以 1 递增。该对象缓存 10 个值以提高性能。cache 选项规定了为了提高访问速度要存储多少个序列值。

要在Persons表中插入新纪录,必须使用 nextval 函数(该函数从seq_person序列中取回下一个值):

Insert into Persons (ID,Firstname,Lastname) values (seq_person.nextval,’miki’,’xue')

上面的 SQL 语句会在 "Persons" 表中插入一条新记录。"ID" 列会被赋值为来自 seq_person 序列的下一个数字。"FirstName"列 会被设置为 “miki","LastName" 列会被设置为 “xue”。

condition 条件

discontinued 停产;已停产

above 在……之上;大于

category 类别

View 视图是可视化的表。视图包含行和列,视图中的字段就是来自一个或多个数据库中的真实的表中的字段。

Create view view_name as

Select column_name(s)

From table_name

Where condition

注释:视图总是显示最新的数据!每当用户查询视图时,数据库引擎通过使用视图的 SQL 语句重建数据。

视图 "Current Product List" 会从 "Products" 表列出所有正在使用的产品(未停产的产品):

Create view [current product list] as

Select ProductID,ProductName

From Products

Where Discontinued = No

查询上面这个视图:

Select * from [current product list]

Northwind 样本数据库的另一个视图会选取 "Products" 表中所有单位价格高于平均单位价格的产品:

Create view [Products Above Average Price] as

Select ProductName,UnitPrice

From Products

where UnitPrice > (Select avg(UnitPrice) from Products)

查询上面这个视图:

Select * from [Products Above Average Price]

计算在 1997 年每个种类的销售总数:

Create view [Category Sales For 1997] as

Select distinct CategoryName,Sum(ProductSales) as CategorySales

From [Product Sales Fro 1997]

Group by CategoryName

查询上面这个视图:

Select * from [Category Sales For 1997]

也可增加查询条件。仅查看Beverages类的销售数据

Select * from [Category Sales For 1997] where CategoryName=‘Beverages'

更新视图

Create or replace view view_name as

Select column_name(s)

From table_name

Where condition

向 "Current Product List" 视图添加 "Category” 列:

Create view [Current Product List] as

Select ProductID,ProductName,Category

From Products

Where Discontinued=No

【SQL Server】

ALTER VIEW [ schema_name . ] view_name [ ( column [ ,...n ] ) ]

[ WITH [ ,...n ] ]

AS select_statement

[ WITH CHECK OPTION ] [ ; ]

::=

{

    [ ENCRYPTION ]

    [ SCHEMABINDING ]

    [ VIEW_METADATA ]    

}

Schema_name:视图所属架构的名称

view_name:要更改的视图

Column:将成为制定视图的一部分的一个或多个列的名称(以逗号分隔)

撤销视图

Drop view view_name

extract 提取;选取

datediff 日期差异    

format 安排……的版式;格式

convert 转换;转变

datetime 日期时间

timestamp 时间戳

Date 函数

处理日期时候,确保所插入的日期格式,与数据库中日期列格式相匹配,比较难。

【MySQL】重要的内建日期函数:

now()    返回当前的日期和时间

curdate()    返回当前的日期

curtime()    返回当前的时间

date()    提取日期或日期/时间表达式的日期部分

extract()    返回日期/时间的单独部分

date add()    向日期添加指定的时间间隔

date sub()    从日期减去指定的时间

datediff()    返回两个日期之间的天数

date format()    用不同的格式显示日期/时间

Select now(),curdate(),curtime()    //返回当前日期和时间,返回当前日期,返回当前时间

Create table Orders(

OrderId int not null,

ProductName varchar(255) not null,

OrderDate datetime not null default now(),

Primary key (OrderId)

)

在Orders表中插入一条数据:

Insert into Orders(ProductName) values (‘abc’)

(下面查询语句也用此表数据)

Select ProductName,date(OrderDate) as OrderDate    //date()提取日期或日期/时间表达式的日期部分

Form Orders

Where OrderId=1

Select extract(year from OrderDate) as OrderYear,    //Extract(unit from date) 返回日期/时间的单独部分,如年、月、日、小时、分钟等。

Extract(month from OrderDate) as OrderMonth,

Extract(day from OrderDate) as OrderDay

From Orders

where OrderId=1

extract函数中date参数是合法的日期表达式,Unit 参数可以是下列的值:

microsecond    //微秒

second    //秒

minute    //分钟

hour

Day

Week

Month

quarter    //季度

Year

Second_microsecond    //秒微秒

Minute_microsecond    //分钟微秒

Minute_second

Hour_microsecond

Hour_second

Hour_minute

Day_microsecond

Day_second

Day_minute

Day_hour

Year_month    //年月

向 "OrderDate" 添加 45 天,找到付款日期:

Select OrderID,date_add(OrderDate,interval 45 day) as OrderPayDate    //date_add(date, interval expr type)向日期添加指定的时间间隔。

From Orders 

date参数是合法的日期表达式。expr参数是添加的时间间隔。type参数可选范围与extrat()函数的unit相同。

向 "OrderDate" 减去 5 天:

Select OrderID,date_sub(OrderDate,interval 5 day) as SubtractDate    //date_sub(date, interval expr type)向日期减去指定的时间间隔。

From Orders

date参数是合法的日期表达式。expr参数是添加的时间间隔。type参数可选范围与extrat()函数的unit相同。

Select datediff(‘2022-6-1’,’2022-6-2’) as diffdate    //datediff(date1,date2)返回两个日期之间的天数。只有值的日期部分参与计算。date1和date2参数是合法的日期或日期/时间表达式。

Select datediff(‘2022-6-2’,’2022-6-1') as diffdate

date_format(date,format)以不同格式显示日期/时间数据。

DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p')

DATE_FORMAT(NOW(),'%m-%d-%Y')

DATE_FORMAT(NOW(),'%d %b %y')

DATE_FORMAT(NOW(),'%d %b %Y %T:%f')

结果如下:

Nov 04 2008 11:45 pm

11-04-2008

04 Nov 08

04 Nov 2008 11:45:34:243

【SQL Server】重要的内建日期函数:

getdate()    返回当前的日期和时间

datepart()    返回日期/时间的单独部分

dateadd()    在日期中添加或减去指定的时间间隔

datediff()    返回两个日期之间的时间

convert()    用不同的格式显示日期/时间

Select getdate() as CurrentDateTime    //getdate()返回当前的日期和时间

Create table Orders(

OrderID int not null primary key,

ProductName varchar(50) not null,

OrderDate datetime not null default getdate()    //OrderDate列自动获取系统当前日期和时间

)

Insert into Orders(ProductName) values (‘abc’)    //插入数据时,Orderdate列自动插入当前日和和时间

Select datepart(yyyy,OrderDate) as OrderYear,    //datepart(datepart,date)返回日期/时间的单独部分,如年、月、日、小时、分钟等

datepart(mm,OrderDate) as OrderMonth,

Datepart(dd,OrderDate) as OrderDay,

From Orders

Where OrderId=1

date参数是合法的日期表达式。datepart参数可以是下列值:

datepart    缩写

年    yy, yyyy

季度    qq, q

月    mm, m

年中的日    dy, y

日    dd, d

周    wk, ww

星期    dw, w

小时    hh

分钟    mi, n

秒    ss, s

毫秒    ms

微妙    mcs

纳秒    ns

向 "OrderDate" 添加 45 天,这样就可以找到付款日期:

Select OrderId,dateadd(day,45,OrderDate) as OrderDate    //dateadd(datepart,number,date)在日期中添加或减去指定的时间间隔。

From Orders

date参数是合法的日期表达式。number是添加的间隔数,未来时间使用正数,过去时间使用负数。

datepart参数范围与datepart()函数的datepart参数相同。

Select datediff(day,’2008-06-05’,’2008-08-05’) as DiffDate    //datediff(datepart,startdate,enddate)返回两个日期之间的天数

Select datediff(day,’2008-08-05’,’2008-06-05’) as DiffDate

startdate和enddate参数是合法的日期表达式。datepart参数的值范围与datepart()函数的datepart参数相同。

Convert(date_type(length),expression,style)函数把日期转换为新数据类型的通用函数。可以用不同的格式显示日期/时间数据。

Date_type(length) 规定目标数据类型(带有可选的长度)

Expression 规定需要转换的值

Style 规定日期/时间的输出格式

查询语句:

SELECT CONVERT(INT, 25.65);

SELECT CONVERT(VARCHAR(19),GETDATE())

SELECT CONVERT(VARCHAR(10),GETDATE(),10)

SELECT CONVERT(VARCHAR(10),GETDATE(),110)

SELECT CONVERT(VARCHAR(11),GETDATE(),6)

SELECT CONVERT(VARCHAR(11),GETDATE(),106)

SELECT CONVERT(VARCHAR(24),GETDATE(),113)

结果:

25

Apr 15 2021 7:59AM

04-15-21

04-15-2021

15 Apr 21

15 Apr 2021

15 Apr 2021 08:03:37:767

SQL Date 数据类型

MySQL 使用下列数据类型在数据库中存储日期或日期/时间值:

DATE - 格式:YYYY-MM-DD

DATETIME - 格式:YYYY-MM-DD HH:MM:SS

TIMESTAMP - 格式:YYYY-MM-DD HH:MM:SS

YEAR - 格式:YYYY 或 YY

SQL Server 使用下列数据类型在数据库中存储日期或日期/时间值:

DATE - 格式:YYYY-MM-DD

DATETIME - 格式:YYYY-MM-DD HH:MM:SS

SMALLDATETIME - 格式:YYYY-MM-DD HH:MM:SS

TIMESTAMP - 格式:唯一的数字

从上表中选取 OrderDate 为 "2008-11-11" 的记录:

Select * from Orders where OrderDate=‘2008-11-11'

如果表中日期含有时间部分,那么将得不到结果,因为表中没有"2008-11-11 00:00:00”日期。

null    值代表遗漏的位置数据。null用作未知的或不适用的值的占位符。无法比较null和0,它们是不等价的。null值无法用比较运算符来测试,比如=,<,<>,必须使用is null或is not null操作符。

选取在 "Address" 列中带有 NULL 值的记录:

Select * from Persons where Adress is null

选取在 "Address" 列中不带有 NULL 值的记录:

Select * from Persons where Adress is not null

SQL ISNULL()、NVL()、IFNULL() 和 COALESCE() 函数

假如 "UnitsOnOrder" 是可选的,而且可以包含 NULL 值:

Select ProductName,UnitPrice*(UnitInstock+UnitOnOrder) from Products

将null值处理为0:

【SQL Server/MS Access】

Select ProductName,UnitPrice*(UnitInstock+isnull(UnitOnOrder,0)) from Products

【Oracle】

Select ProductName,UnitPrice*(UnitInstock+nvl(UnitOnOrder,0)) from Products

【MySQL】

Select ProductName,UnitPrice*(UnitInstock+ifnull(UnitOnOrder,0)) from Products

Select ProductName,UnitPrice*(UnitInstock+coalesce(UnitOnOrder,0)) from Products

SQL 通用数据类型:

数据类型    描述

character(n)    字符/字符串。固定长度 n。

varchar(n) 或 character varying(n)    字符/字符串。可变长度。最大长度 n。

binary(n)    二进制串。固定长度 n。

boolean    存储 TRUE 或 FALSE 值

varbinary(n) 或

binary varying(n)    二进制串。可变长度。最大长度 n。

integer(p)    整数值(没有小数点)。精度 p。

smallint    整数值(没有小数点)。精度 5。

integer    整数值(没有小数点)。精度 10。

bigint    整数值(没有小数点)。精度 19。

decimal(p,s)    精确数值,精度 p,小数点后位数 s。例如:decimal(5,2) 是一个小数点前有 3 位数,小数点后有 2 位数的数字。

numeric(p,s)    精确数值,精度 p,小数点后位数 s。(与 DECIMAL 相同)

float(p)    近似数值,尾数精度 p。一个采用以 10 为基数的指数计数法的浮点数。该类型的 size 参数由一个指定最小精度的单一数字组成。

real    近似数值,尾数精度 7。

float    近似数值,尾数精度 16。

double precision    近似数值,尾数精度 16。

date    存储年、月、日的值。

time    存储小时、分、秒的值。

timestamp    存储年、月、日、小时、分、秒的值。

interval    由一些整数字段组成,代表一段时间,取决于区间的类型。

array    元素的固定长度的有序集合

multiset    元素的可变长度的无序集合

xml    存储 XML 数据

参考网址:https://www.runoob.com/sql/sql-datatypes-general.html

参考网址:https://www.runoob.com/sql/sql-datatypes.html

Aggregate 合计;总计

Scalar 变量;标量变量

【SQL Aggregate 函数】

SQL Aggregate 函数计算从列中取得的值,返回一个单一的值。

有用的 Aggregate 函数:

AVG() - 返回平均值

COUNT() - 返回行数

FIRST() - 返回第一个记录的值

LAST() - 返回最后一个记录的值

MAX() - 返回最大值

MIN() - 返回最小值

SUM() - 返回总和

【SQL Scalar 函数】

SQL Scalar 函数基于输入值,返回一个单一的值。

有用的 Scalar 函数:

UCASE() - 将某个字段转换为大写

LCASE() - 将某个字段转换为小写

MID() - 从某个文本字段提取字符,MySql 中使用

SubString(字段,1,end) - 从某个文本字段提取字符

LEN() - 返回某个文本字段的长度

ROUND() - 对某个数值字段进行指定小数位数的四舍五入

NOW() - 返回当前的系统日期和时间

FORMAT() - 格式化某个字段的显示方式

avg() 函数返回数值列的平均值。

从 "access_log" 表的 "count" 列获取平均值:

Select avg(count) as CountAverage from access_log;

选择访问量高于平均访问量的 "site_id" 和 “count":

Select site_id,count from access_log where count > (select avg(count) from access_log);

count() 函数返回匹配指定条件的行数。

Select count(column_name) from table_name;    //count(column_name)函数返回指定列的值的数目(null不计入)

Select count(*) from table_name;    //count(*)函数返回表中的记录数

Select count(distinct column_name) from table_name;    //count(distinct column_name) 函数返回指定列的不同值的数目

注释:COUNT(DISTINCT) 适用于 ORACLE 和 Microsoft SQL Server,但是无法用于 Microsoft Access。

计算 "access_log" 表中 "site_id"=3 的总访问量:

Select count(count) as nums from access_log where site_id=3;

计算 "access_log" 表中总记录数:

Select count(*) as nums from access_log;

计算 "access_log" 表中不同 site_id 的记录数:

Select count(distinct site_id) as nums from access_log;

first() / last() 函数返回指定的列中 第一个/最后一个 记录的值。

Select first(column_name) from table_name;    //注释:只有 MS Access 支持 FIRST() LAST()函数。

Select last(column_name) from table_name;

选取 "Websites" 表的 "name" 列中第一个记录的值:

Select name as FirstSite from Websites limit 1;

选取 "Websites" 表的 "name" 列中最后一个记录的值:

Select name from Websites order by id desc limit 1;

SQL Server、MySQL 和 Oracle 中的 SQL FIRST() / LAST()工作区

【SQL Server】

语法:Select top 1 column_name from table_name order by column_name asc;

语法:Select top 1 column_name from table_name order by column_name desc;

实例:select top 1 name from websites order by id asc;

【MySQL】

语法:select column_name from table_name order by column_name asc limit 1;

语法:select column_name from table_name order by column_name desc limit 1;

实例:select name from websites order by id asc limit 1;

【Oracle】

语法:select column_name from table_name order by column_name asc where rownum <=1;

语法:select column_name from table_name order by column_name desc where rownum <=1;

实例:select name from Websites order by id asc where rownum <=1;

Max()/min() 函数返回指定列的最大值/最小值。

语法:select max(column_name) from table_name;

语法:select min(column_name) from table_name;

从 "Websites" 表的 "alexa" 列获取最大值:

Select max(alexa) as max_alexa from Websites;

sum() 函数返回数值列的总数。

查找 "access_log" 表的 "count" 字段的总数:

Select sum(count) as nums from access_log;

Group by 语句可结合聚合函数来使用,根据一个或多个列对结果集进行分组。

语法:

Select column_name,aggregate_function(column_name)

From table_name

Where column_name operator value

Group by column_name;

【group by 简单应用】统计 access_log 各个 site_id 的访问量:

Select site_id,sum(access_log.count) as sums from access_log group by site_id;

【group by 多表连接】统计有访问记录的网站的(记录)数量:

Select Websites.name,count(access_log.aid) as sums from access_log

left join  Websites 

on access_log.site_id=Websites.id

Group by Websites.name;

Having子句 用于筛选分组后的各组数据。增加having子句的原因是 where关键字无法与聚合函数一起使用。

语法:

Select column_name,aggregate_function(column_name)

From table_name

Where column_name operator value

Group by column_name

Having aggregate_function(column_name) operator value;

查找总访问量大于 200 的网站:

Select Websites.name,Websites.url,sum(access_log.count) as nums from (access_log

Inner join Websites

On access_log.site_id=Websites.id)

Group by Websites.name

Having sum(access_log.count) > 200;

查找总访问量大于 200 的网站,并且 alexa 排名小于 200:

Select Websites.name,sum(access_log.count) as nums,Websites.alexa

from WebsitesInner join access_log on Websites.id=access_log.site_id    //推测:此处inner join和left join 结果集相同,所以两者均可?

Where Websites.alexa < 200    //where在group by前,且后不能跟聚合函数,如avg、sum、max、min、count

Group by Websites.name    

Having sum(access_log.count) > 200;    //having在group by 后可跟聚合函数

exists 存在

Condition 条件

Exists 运算符用于判断查询子句是否有记录,如果有一条或多条记录存在返回TRUE,否则返回FALSE

语法:

Select column_name(s) 

from table_name 

where exists

(Select column_name from table_name where condition);

查找总访问量(count 字段)大于 200 的网站是否存在:

Select Websites.name,Websites.url 

from Websites 

where exists

(Select count from access_log where Websites.id=access_log.site_id and count >200);

EXISTS 可以与 NOT 一同使用,查找出不符合查询语句的记录:

Select Websites.name,Websites.url 

from Websites

where not exists

(Select count from access_log where Websites.id=access_log.site_id and count >200);

Lower case to upper case 小写转大写

Ucase() 函数把字段的值转化为大写。

Lcase() 函数把字段的值转化为小写。

语法:

Select ucase(column_name) from table_name;

【SQL Server】select upper(column_name) from table_name;

Select lcase(column_name) from table_name;

【SQL Server】select lower(column_name) from table_name;

从 "Websites" 表中选取 "name" 和 "url" 列,并把 "name" 列的值转换为大写:

Select ucase(name) as site_title,url from Websites;

从 "Websites" 表中选取 "name" 和 "url" 列,并把 "name" 列的值转换为小写:

Select lcase(name) as site)title,url from Websites;

Mid() 函数用于从文字字段中提取字符。

语法:

Select mid(column_name,start,[length]) from table_name;

参数    描述

column_name    必需。要提取字符的字段。

start    必需。规定开始位置(起始值是 1)。

length    可选。要返回的字符数。如果省略,则 MID() 函数返回剩余文本。

从 "Websites" 表的 "name" 列中提取前 4 个字符:

Select mid(name,1,4) as ShortTitle from Websites;

Len() 函数返回文本段值的长度。

语法:

Select len(column_name) from table;

【MySQL】select length(column_name) from table_name;

从 "Websites" 表中选取 "name" 和 "url" 列中值的长度:

Select name,length(url) as LengthOfURL from Websites;

decimals 小数位数

round() 函数用于把数值字段舍入为指定的小数位数。

语法:

Select round(column_name,decimals) from table_name;

参数    描述

column_name    必需。要舍入的字段。

decimals    可选。规定要返回的小数位数。

Select round(-1.23);

Select round(-1.58);

Select round(1.58);

Select round(1.298,1);

Select round(1.298,0);

Now() 函数返回当前系统的日期和时间。

语法:Select now() from table_name;

从 "Websites" 表中选取 name,url,及当天日期:

Select name, url,now() as date from Websites;

format 格式化

Format() 函数用于对字段的显示进行格式化。

语法:select format(column_name,format) from table_name;

参数    描述

column_name    必需。要格式化的字段。

format    必需。规定格式。

从 "Websites" 表中选取 name, url 以及格式化为 YYYY-MM-DD 的日期:

Select name, url,date_format(now(),'%Y-%m-%d’) as date from Websites;

IF 表达式

IF( expr1 , expr2 , expr3 )

expr1 的值为 TRUE,则返回值为 expr2

expr1 的值为FALSE,则返回值为 expr3

SQL赋值语句

@表示声明一个局部变量,@@表示声明一个全局变量(比如已经定义好的系统变量)

申请局部变量语法:declare @变量名 数据类型;例如declare@num int;

赋值:有两种方式(@为变量名,vlaue为值)

Set @num=value    或        select @num=value;

declare @count表示选定变量

select @count=1     或    set @count=1    均表示为count赋值1,但select和set赋值有区别。select可以在一条语句里对多个变量同时赋值,而set只能一次对一个变量赋值,即如果数据表中存在多个count变量,则不能使用set赋值。

例:

将变量count值赋值为1

declare @count select @count=1

group_concat文本组合

separator 分隔符

group_concat默认使用逗号隔开:

SELECT GROUP_CONCAT(changjing) FROM datafrog_test1;

去重:

SELECT GROUP_CONCAT(DISTINCT inttime) FROM datafrog_test1;

排序:

SELECT GROUP_CONCAT(DISTINCT inttime ORDER BY inttime DESC) FROM datafrog_test1;

设置分隔符:

SELECT GROUP_CONCAT(DISTINCT inttime ORDER BY inttime DESC SEPARATOR';') FROM datafrog_test1;

Case…when 用于选择判断,在执行时先对条件进行判断,然后根据判断结果做出相应操作。case函数只要满足某个条件后,剩下的条件将会被自动忽略,因此即使满足多个条件,执行过程中也只认第一个条件。

语法:

case 字段 when 条件1 then 操作1 

                 when 条件2 then 操作2

                 …

                 else 操作n

                 End;

简单case函数:

Case sex 

    when 1 then ‘男’

    when 0 then ‘女'

else ‘其他’end;

Case搜索函数:

Case when sex=1 then ‘男’

         when sex=0 then ‘女’

         else ‘其他' end;

substring_index(string,sep,num)    截取目标字符串

即substring_index(字符串,分隔符,序号)

参数说明

string:用于截取目标字符串的字符串。可为字段,表达式等。

sep:分隔符,string存在且用于分割的字符,比如“,”、“.”等。

num:序号,为非0整数。若为整数则表示从左到右数,若为负数则从右到左数。比如“www.mysql.com”截取字符‘www’,分割符为“.”,从左到右序号为1,即substring_index("www.mysql.com",'.',1);若从右开始获取“com”则为序号为-1即substring_index("www.mysql.com",'.',-1)

你可能感兴趣的:(【完结✅】SQL基础知识复习)