百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

超详细的sql语句汇总

toyiye 2024-06-21 12:35 9 浏览 0 评论



请创建如下表,并创建相关约束


use test

-- 创建班级表 --

create table class(cid int primary key auto_increment,caption varchar(20) not null)

insert into class(caption) values('三年二班'),('一年三班'),('三年一班')

drop table class;

select * from class;

-- 创建一个教师表 --

create table teacher(tid int primary key auto_increment,tname varchar(20) not null)

insert into teacher(tname) values('波多'),('长空'),('饭岛')

select * from teacher

-- 创建一个学生表 --

create table student(

sid int primary key auto_increment,

sname varchar(20) not null,

gender char not null,

class_id int not null,

foreign key(class_id) references class(cid) -- 外键,引用班级表的cid

)

insert into student(sname,gender,class_id) values('小刚','男',1),('小红','女',1),('小蓝','女',2)

select * from student

-- 创建一个课程表 --

create table course(

cid int primary key auto_increment,

cname varchar(20) not null,

tearch_id int not null,

foreign key(tearch_id) references teacher(tid)

)

insert into course(cname,tearch_id) values('生物',1),('体育',1),('物理',2)

select * from course

-- 创建一个成绩表 --

create table score(score_id int primary key auto_increment,student_id int not null,

corse_id int not null,

number int not null,

foreign key(student_id) references student(sid),

foreign key(corse_id) references course(cid)

)

insert into score(student_id,corse_id,number) values(1,1,60),(1,2,59),(2,2,100)

select * from score

show tables

select * from class,teacher,student,course,score


DROP TABLE IF EXISTS `emp`;

CREATE TABLE `emp` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`NAME` varchar(10) DEFAULT NULL,

`gender` char(1) DEFAULT NULL,

`salary` double DEFAULT NULL,

`join_date` date DEFAULT NULL,

`dept_id` int(11) DEFAULT NULL,

PRIMARY KEY (`id`),

KEY `dept_id` (`dept_id`)

) ENGINE=MyISAM AUTO_INCREMENT=993 DEFAULT CHARSET=utf8;

-- ------------------------------ Records of emp-- ----------------------------

INSERT INTO `emp` VALUES ('1', '孙悟空', '男', '7200', '2013-02-24', '1');

INSERT INTO `emp` VALUES ('2', '猪八戒', '男', '7000', '2010-12-02', '2');

INSERT INTO `emp` VALUES ('3', '唐僧', '男', '9000', '2008-08-08', '2');

INSERT INTO `emp` VALUES ('4', '白骨精', '女', '5000', '2015-10-07', '3');

INSERT INTO `emp` VALUES ('5', '蜘蛛精', '女', '4500', '2011-03-14', '1');\

select * from emp

select * from emp where if (dept_id=1,dept_id,0);

create procedure p_test(in s int) begin if s < 5000

then select name,salary,gender from emp where salary <5000;

else

select * from emp where salary > 5000;

end if;

end

call p_test(1000);

综合使用 查询 目录:

#----综合使用

书写顺序

select distinct * from '表名' where '限制条件' group by '分组依据' having '过滤条件' order by limit '展示条数'

执行顺序

from -- 查询

where -- 限制条件

group by -- 分组

having -- 过滤条件

order by -- 排序

limit -- 展示条数

distinct -- 去重

select -- 查询的结果

正则:select * from emp where name regexp '^j.*(n|y)#39;;

集合查询:max 、min 、avg 、sum 、count 、group_concat 。

内连接:inner join

左连接:left join

右连接:right join

全连接: 左连接 union 右连接

replace 替换

拼接:concat、concat_ws、group_concat

常规设置操作

1.服务器设置远程访问

grant all privileges on *.* to 'root'@'%' identified by '123456' with grant option;

2.Linux中数据库的基本操作命令

1.使用service

启动:service mysql start

停止:service mysql stop

重启:service mysql restart

2.清屏:clear,reset

3.备份数据库

#mysqldump -uroot -p密码 数据库名 > D:/备份文件名.sql

4.恢复备份的数据库

#首先在mysql里建好数据库名

#mysql -uroot -p密码 数据库名 < D:/备份文件名.sql

5.查询binlog日志是否开启

show variables like 'log_%';

基本操作:

1.单表约束

#主键约束:PRIMARY KEY 要求被装饰的字段:唯一和非空

#唯一约束:UNIQUE 要求被装饰的字段:唯一,

# .联合唯一:在结尾:unique(字段1,字段2)

#非空约束:NOT NULL 要求被装饰的字段:非空

#外键约束:FOREIGN KEY 某主表的外键

#自动增加:AUTO_INCREMENT 自动增加(需要和主键 PRIMARY KEY 同时用)

#设置默认值:DEFAULT 为该属性设置默认值

# 在int、char中:zerofill 不足位数默认填充0


2.常用数据类型

int #整型,4个字节 一般不需要指定宽度,(8):只是显示为8位,默认有负号设置无负号: unsigned

double #浮点型,例如double(5,2),标识最多5位,其中2位为小数,即最大为999.99

varchar #可变长度字符串类型。例如:varchar(10) 'aaa' 占3位

char #固定长度字符串类型。例如:char(10) 'aaa' 占10位

text #大文本字符串类型。

blob #字节类型。例如:

datetime #日期时间类型。例如:datetime(yyyy-MM-dd hh:mm:ss)

date #日期类型。例如:date(yyyy:MM:dd)

time #时间类型。例如:time(hh:mm:ss)

timestamp #时间戳类型。例如:timestamp(yyyy-MM-dd hh:mm:ss) 会自动赋值

enum #枚举 多选一 enum('male','female'),default为默认值

例如:sex enum('male','female') not null default 'male'

set #集合 多选多,可以选一个 set('read','DJ','DBJ','run')

注:字符串类型和时间类型都要用单引号括起来,空值为null

3.查看数据列表

show databases; -- 查看所有数据库

show create table 表名; -- 查看表的创建细节

desc 表名; -- 查看表结构

4.进入数据库

#use 数据名

use Python_7

5.创建数据库

#CREATE DATABASE 数据库名

CREATE DATABASE Python_7;

CREATE DATABASE pyrhon_7 charset utf8

# 修改数据库编码

alter database db1 charset gbk;

6.删除数据库

#drop database 需要删除的数据库名

drop database Python_7;

7.查看表

select database(); # 查看当前所在的库

show tables; -- 查看数据库中所有表

desc 表名; -- 查看表结构

show create table 表名; -- 查看表的创建细节

8.创建表

# 创建新表

# create table 新建数据表名(

# 字段名 类型(长度) [约束(具体见1)],

# 字段名 类型(长度) [约束(具体见1)]

# );

create table class(

id INT AUTO_INCREMENT,

name varchar(32) UNIQUE,

age varchar(32) NOT NULL

);

#需要注意

#根据已有的表创建新表

create table 新表 like 旧表 -- 使用旧表创建新表

create table 新表 as select 字段1 字段2... from definition only -- 使用自定义值去新建表

9.删除表

#drop table 数据库表名

drop table Python

10.修改表

alter table 表名 add 字段名 类型(长度) [约束]; -- 添加列

alter table 表名 modify 字段名 类型(长度) [约束]; -- 修改列的类型长度及约束

alter table 表名 change 旧字段名 新字段名 类型(长度) [约束]; -- 修改列表名

alter table 表名 drop 字段名; -- 删除列

alter table 表名 character set 字符集; -- 修改表的字符集

rename table 表名 to 新表名; -- 修改表名

11.增加数据

insert into 表(字段名1,字段名2..) values(值1,值2..);-- 向表中插入某些列

insert into 表 values(值1,值2,值3..); -- 向表中插入所有列

12.修改数据

update 表名 set 字段名=值,字段名=值...; -- 这个会修改所有的数据,把一列的值都变了

update 表名 set 字段名=值,字段名=值... where 条件; -- 只改符合where条件的行

13.删除数据

delete from 表名 -- 删除表中所有记录

delete from 表名 where 条件 -- 删除符合 where条件的数据

truncate table 表名; -- 把表直接drop掉,重新建表,auto_increment将置为零。删除的数据不能找回。执行速度比delete快

14.数据的简单查询

select * from 表名; -- 查询所有列

select 字段名1,字段名2,字段名3.. from 表名; -- 查询指定列

15.几个简单的基本的sql语句

select * from 表名 where 范围 -- 选择查询

insert into 表名(field1,field2) values(value1,value2) -- 插入

delete from 表名 where 范围 -- 删除

update 表名 set field1=value1 where 范围 -- 更新

select * from 表名 where field1 like ’%value1%’ -- 查找

select * from 表名 order by field1,field2 [desc] -- 排序:

select count as 需要统计总数的字段名 from 表名 -- 总数

select sum(field1) as sumvalue from 表名 -- 求和

select avg(field1) as avgvalue from 表名 -- 平均

select max(field1) as maxvalue from 表名 -- 最大

select min(field1) as minvalue from 表名 -- 最小

16.存储引擎

# 查看所有的存储引擎

show engines;

# 查看不同存储引擎存储表结构文件特点

create table t1(id int)engine=innodb; -- MySQL默认的存储引擎,支持事务,支持行锁,支持外键。有且只有一个主键,用来组织数据的依据

create table t2(id int)engine=myisam; -- 不支持事务,不支持外键,支持全文索引,处理速度快。

create table t3(id int)engine=blackhole; -- 黑洞,写入它的任何内容都会消失

create table t4(id int)engine=memory;-- 将表中的数据存储在内存中。表结构以文件存储于磁盘。

insert into t1 values(1);

insert into t2 values(1);

insert into t3 values(1);

insert into t4 values(1);

17.设置严格模式

# 查询

show variables like '%mode%';

# 设置

set session -- 设置当前窗口下有效

set global -- 全局有效,终身受用

set global sql_mode = "STRICT_TRANS_TABLES";

# 设置完成后需要退出客户端,重新登录客户端即可,不需要重启服务端

group by分组涉及到的模式:

设置sql_mode为only_full_group_by,意味着以后但凡分组,只能取到分组的依据,

不应该在去取组里面的单个元素的值,那样的话分组就没有意义了,因为不分组就是对单个元素信息的随意获取

"""

set global sql_mode="strict_trans_tables,only_full_group_by";

# 重新链接客户端

18.like 的用法

A:% 包含零个或多个字符的任意字符串:

1、like'Mc%' 将搜索以字母 Mc 开头的所有字符串(如 McBadden)。

2、like'%inger' 将搜索以字母 inger 结尾的所有字符串(如 Ringer、Stringer)。

3、like'%en%' 将搜索在任何位置包含字母 en 的所有字符串(如 Bennet、Green、McBadden)。

B:_(下划线) 任何单个字符:

like'_heryl' 将搜索以字母 heryl 结尾的所有六个字母的名称(如 Cheryl、Sheryl)。

C:[ ] 指定范围 ([a-f]) 或集合 ([abcdef]) 中的任何单个字符:

1,like'[CK]ars[eo]n' 将搜索下列字符串:Carsen、Karsen、Carson 和 Karson(如 Carson)。

2、like'[M-Z]inger' 将搜索以字符串 inger 结尾、以从 M 到 Z 的任何单个字母开头的所有名称(如 Ringer)。

D:[^] 不属于指定范围 ([a-f]) 或集合 ([abcdef]) 的任何单个字符:

like'M[^c]%' 将搜索以字母 M 开头,并且第二个字母不是 c 的所有名称(如MacFeather)。

E:* 它同于DOS命令中的通配符,代表多个字符:

c*c代表cc,cBc,cbc,cabdfec等多个字符。

F:?同于DOS命令中的?通配符,代表单个字符 :

b?b代表brb,bFb等

G:# 大致同上,不同的是代只能代表单个数字。k#k代表k1k,k8k,k0k 。

下面我们来举例说明一下:

例1,查询name字段中包含有“明”字的。

select * from table1 where name like '%明%'

例2,查询name字段中以“李”字开头。

select * from table1 where name like '李*'

例3,查询name字段中含有数字的。

select * from table1 where name like '%[0-9]%'

例4,查询name字段中含有小写字母的。

select * from table1 where name like '%[a-z]%'

例5,查询name字段中不含有数字的。

select * from table1 where name like '%[!0-9]%'

以上例子能列出什么值来显而易见。但在这里,我们着重要说明的是通配符“*”与“%”的区别。

很多朋友会问,为什么我在以上查询时有个别的表示所有字符的时候用"%"而不用“*”?先看看下面的例子能分别出现什么结果:

select * from table1 where name like '*明*'

select * from table1 where name like '%明%'

大家会看到,前一条语句列出来的是所有的记录,而后一条记录列出来的是name字段中含有“明”的记录,所以说,当我们作字符型字段包含一个子串的查询时最好采用“%”而不用“*”,用“*”的时候只在开头或者只在结尾时,而不能两端全由“*”代替任意字符的情况下。

高级查询操作

1、外键表创建

一对多(Foreign Key)

# foreign key(需要关联的本字段) references 需要关联对表的表(需要关联对表的字段)

例如:

创建dep

foreign key(dep_id) references dep(id)

# 同步更新,同步删除

on update cascade #同步更新

on delete cascade #同步删除

2、表复制

复制表

create table t1 select * from test;

只复制表结构

create table t1 select * from test where 1=2;

3、单表查询查询

0.综合使用

#----综合使用

书写顺序

select distinct * from '表名' where '限制条件' group by '分组依据' having '过滤条件' order by limit '展示条数'

执行顺序

from -- 查询

where -- 限制条件

group by -- 分组

having -- 过滤条件

order by -- 排序

limit -- 展示条数

distinct -- 去重

select -- 查询的结果

正则:select * from emp where name regexp '^j.*(n|y)#39;;

集合查询:max 、min 、avg 、sum 、count 、group_concat 。

拼接:concat、concat_ws、group_concat

内连接:inner join

左连接:left join

右连接:right join

全连接: 左连接 union 右连接

1.where 查询

# between 在...之间

select id,name from emp where id >= 3 and id <= 6;

相当于:

select * from emp where id between 3 and 6;

# or 或者

select * from emp where id >= 3 or id <= 6;

# in,后面可以跟多个值

select * from 表名 where 字段名 in (条件1,条件2,条件三);

# like (见上18)

# char——length() 取字符长度

select * from 表名 where char_length(需要获取长度的字段名) = 4;

not 配合使用

注意:判断空不能用 = ,只能用 is

2.group by 分组

select 查询字段1,查询字段2,... from 表名

where 过滤条件

group by分组依据 # 分组后取出的是每个组的第一条数据

3.聚合查询 :以组为单位统计组内数据>>>聚合查询(聚集到一起合成为一个结果)

# max 最大值

# 每个部门的最高工资

select post,max(salary) from emp group by post;

# min 最小值

# 每个部门的最低工资

select post,min(salary) from emp group by post;

# avg 平均值

# 每个部门的平均工资

select post,avg(salary) from emp group by post;

# 每个部门的工资总和

# sum 求和

select post,sum(salary) from emp group by post;

# count(需要计数字段) 计数

# 每个部门的人数

select post,count(id) from emp group by post;

# group_concat(需要分组后的字段) # 不仅可以用来显示除分组外字段还有拼接字符串的作用

select post,group_concat(name) from emp group by post;

-- post:分组字段,name 需要分组后显示的字段

拼接:

concat(不分组时用)拼接字符串达到更好的显示效果 as语法使用

举例:

select concat("NAME: ",name) as 姓名 from emp;

concat_ws: 如果拼接的符号是统一的可以用

举例:

select concat_ws(':',name,age,sex) as info from emp;

group_concat:

举例:

select post,group_concat(name,'DSB') from emp group by post;


补充:as语法 起别名

select name as 姓名,salary as 薪资 from emp;

4.having 过滤查询

# having的语法格式与where一致,只不过having是在分组之后进行的过滤,即where虽然不能用聚合函数,但是having可以!

# 用法

select 查询字段1,查询字段2,... from 表名

where 过滤条件1

group by分组依据

having avg(过滤条件2) > 10000;

5.distinct 去重

# 对有重复的展示数据进行去重操作

select distinct 需取重字段 from 表名;

6.order by 排序

select * from emp order by salary asc; #默认升序排

select * from emp order by salary desc; #降序排

# 多条件排序

#先按照age降序排,在年轻相同的情况下再按照薪资升序排

select * from emp order by age desc,salary asc;

7.limit 限制展示条数

# 限制展示条数

select * from emp limit 3;

# 查询工资最高的人的详细信息

select * from emp order by salary desc limit 1;

# 分页显示

select * from emp limit 0,5; # 第一个参数表示起始位置,第二个参数表示的是条数,不是索引位置

select * from emp limit 5,5;

8.正则

select * from emp where name regexp '^j.*(n|y)#39;;

9.replace 替换

replace(str1,old,new) -- str1:需要替换的字段名

update gd_km set mc=replace(mc,'土地','房子')

说明:new替换str1中出现的所有old,返回新的字符串,如果有某个参数为NULL,此函数返回NULL

该函数可以多次替换,只要str1中还有old存在,最后都被替换成new

若new为空,则删除old

四、多表查询

1.内连接、左连接、右连接、全连接

1、内连接:只取两张表有对应关系的记录(只拼两个表共有的)

左表 inner join 右表 on 条件

select * from emp inner join dep on emp.dep_id = dep.id

where dep.name = "技术";

2、左连接:在内连接的基础上,保留左边的数据,右边没有就为空

左表 inner left 右表 on 条件

3、右连接:在内连接的基础上,保留右边的数据,左边没有就为空

左表 inner right 右表 on 条件

4、全连接:左右连接都有,用union连接

左表 inner left 右表 on 条件 union 左表 inner right 右表 on 条件

select * from emp left join dep on emp.dep_id = dep.id

union

select * from emp right join dep on emp.dep_id = dep.id;

======================sql server 高级语句=========================

基本常用查询

–select

select * from student;

–all 查询所有

select all sex from student;

–distinct 过滤重复

select distinct sex from student;

–count 统计

select count(*) from student;

select count(sex) from student;

select count(distinct sex) from student;

–top 取前N条记录

select top 3 * from student;

–alias column name 列重命名

select id as 编号, name ‘名称’, sex 性别 from student;

–alias table name 表重命名

select id, name, s.id, s.name from student s;

–column 列运算

select (age + id) col from student;

select s.name + ‘-’ + c.name from classes c, student s where s.cid = c.id;

–where 条件

select * from student where id = 2;

select * from student where id > 7;

select * from student where id < 3;

select * from student where id <> 3;

select * from student where id >= 3;

select * from student where id <= 5;

select * from student where id !> 3;

select * from student where id !< 5;

–and 并且

select * from student where id > 2 and sex = 1;

–or 或者

select * from student where id = 2 or sex = 1;

–between … and … 相当于并且

select * from student where id between 2 and 5;

select * from student where id not between 2 and 5;

–like 模糊查询

select * from student where name like ‘%a%’;

select * from student where name like ‘%[a][o]%’;

select * from student where name not like ‘%a%’;

select * from student where name like ‘ja%’;

select * from student where name not like ‘%[j,n]%’;

select * from student where name like ‘%[j,n,a]%’;

select * from student where name like ‘%[^ja,as,on]%’;

select * from student where name like ‘%[ja_on]%’;

–in 子查询

select * from student where id in (1, 2);

–not in 不在其中

select * from student where id not in (1, 2);

–is null 是空

select * from student where age is null;

–is not null 不为空

select * from student where age is not null;

–order by 排序

select * from student order by name;

select * from student order by name desc;

select * from student order by name asc;

–group by 分组

按照年龄进行分组统计

select count(age), age from student group by age;

按照性别进行分组统计

select count(), sex from student group by sex;

按照年龄和性别组合分组统计,并排序

select count(), sex from student group by sex, age order by age;

按照性别分组,并且是id大于2的记录最后按照性别排序

select count(), sex from student where id > 2 group by sex order by sex;

查询id大于2的数据,并完成运算后的结果进行分组和排序

select count(), (sex * id) new from student where id > 2 group by sex * id order by sex * id;

–group by all 所有分组

按照年龄分组,是所有的年龄

select count(*), age from student group by all age;

–having 分组过滤条件

按照年龄分组,过滤年龄为空的数据,并且统计分组的条数和现实年龄信息

select count(*), age from student group by age having age is not null;

按照年龄和cid组合分组,过滤条件是cid大于1的记录

select count(*), cid, sex from student group by cid, sex having cid > 1;

按照年龄分组,过滤条件是分组后的记录条数大于等于2

select count(*), age from student group by age having count(age) >= 2;

按照cid和性别组合分组,过滤条件是cid大于1,cid的最大值大于2

select count(*), cid, sex from student group by cid, sex having cid > 1 and max(cid) > 2;

嵌套子查询

子查询是一个嵌套在select、insert、update或delete语句或其他子查询中的查询。任何允许使用表达式的地方都可以使用子查询。子查询也称为内部查询或内部选择,而包含子查询的语句也成为外部查询或外部选择。

1

from (select … table)示例

将一个table的查询结果当做一个新表进行查询

select * from (

select id, name from student where sex = 1

) t where t.id > 2;

上面括号中的语句,就是子查询语句(内部查询)。在外面的是外部查询,其中外部查询可以包含以下语句:

1、 包含常规选择列表组件的常规select查询

2、 包含一个或多个表或视图名称的常规from语句

3、 可选的where子句

4、 可选的group by子句

5、 可选的having子句

1

2

3

4

5

6

7

8

9

示例

查询班级信息,统计班级学生人生

select , (select count() from student where cid = classes.id) as num

from classes order by num;

in, not in子句查询示例

查询班级id大于小于的这些班级的学生信息

select * from student where cid in (

select id from classes where id > 2 and id < 4

);

查询不是班的学生信息

select * from student where cid not in (

select id from classes where name = ‘2班’

)

in、not in 后面的子句返回的结果必须是一列,这一列的结果将会作为查询条件对应前面的条件。如cid对应子句的id;

exists和not exists子句查询示例

查询存在班级id为的学生信息

select * from student where exists (

select * from classes where id = student.cid and id = 3

);

查询没有分配班级的学生信息

select * from student where not exists (

select * from classes where id = student.cid

);

exists和not exists查询需要内部查询和外部查询进行一个关联的条件,如果没有这个条件将是查询到的所有信息。如:id等于student.id;

some、any、all子句查询示例

查询班级的学生年龄大于班级的学生的年龄的信息

select * from student where cid = 5 and age > all (

select age from student where cid = 3

);

select * from student where cid = 5 and age > any (

select age from student where cid = 3

);

select * from student where cid = 5 and age > some (

select age from student where cid = 3

);

聚合查询

1、 distinct去掉重复数据

select distinct sex from student;

select count(sex), count(distinct sex) from student;

2、 compute和compute by汇总查询

对年龄大于的进行汇总

select age from student

where age > 20 order by age compute sum(age) by age;

对年龄大于的按照性别进行分组汇总年龄信息

select id, sex, age from student

where age > 20 order by sex, age compute sum(age) by sex;

按照年龄分组汇总

select age from student

where age > 20 order by age, id compute sum(age);

按照年龄分组,年龄汇总,id找最大值

select id, age from student

where age > 20 order by age compute sum(age), max(id);

compute进行汇总前面是查询的结果,后面一条结果集就是汇总的信息。compute子句中可以添加多个汇总表达式,可以添加的信息如下:

a、 可选by关键字。它是每一列计算指定的行聚合

b、 行聚合函数名称。包括sum、avg、min、max、count等

c、 要对其执行聚合函数的列

compute by适合做先分组后汇总的业务。compute by后面的列一定要是order by中出现的列。

1

2

3

4

5

6

7

3、 cube汇总

cube汇总和compute效果类似,但语法较简洁,而且返回的是一个结果集。

select count(), sex from student group by sex with cube;

select count(), age, sum(age) from student where age is not null group by age with cube;

cube要结合group by语句完成分组汇总

? 排序函数

排序在很多地方需要用到,需要对查询结果进行排序并且给出序号。比如:

1、 对某张表进行排序,序号需要递增不重复的

2、 对学生的成绩进行排序,得出名次,名次可以并列,但名次的序号是连续递增的

3、 在某些排序的情况下,需要跳空序号,虽然是并列

基本语法

排序函数 over([分组语句] 排序子句[desc][asc])

排序子句 order by 列名, 列名

分组子句 partition by 分组列, 分组列

row_number函数

根据排序子句给出递增连续序号

按照名称排序的顺序递增

select s.id, s.name, cid, c.name, row_number() over(order by c.name) as number

from student s, classes c where cid = c.id;

rank函数函数

根据排序子句给出递增的序号,但是存在并列并且跳空

顺序递增

select id, name, rank() over(order by cid) as rank from student;

跳过相同递增

select s.id, s.name, cid, c.name, rank() over(order by c.name) as rank

from student s, classes c where cid = c.id;

dense_rank函数

根据排序子句给出递增的序号,但是存在并列不跳空

不跳过,直接递增

select s.id, s.name, cid, c.name, dense_rank() over(order by c.name) as dense

from student s, classes c where cid = c.id;

partition by分组子句

可以完成对分组的数据进行增加排序,partition by可以与以上三个函数联合使用。

利用partition by按照班级名称分组,学生id排序

select s.id, s.name, cid, c.name, row_number() over(partition by c.name order by s.id) as rank

from student s, classes c where cid = c.id;

select s.id, s.name, cid, c.name, rank() over(partition by c.name order by s.id) as rank

from student s, classes c where cid = c.id;

select s.id, s.name, cid, c.name, dense_rank() over(partition by c.name order by s.id) as rank

from student s, classes c where cid = c.id;

ntile平均排序函数

将要排序的数据进行平分,然后按照等分排序。ntile中的参数代表分成多少等分。

select s.id, s.name, cid, c.name,

ntile(5) over(order by c.name) as ntile

from student s, classes c where cid = c.id;

集合运算

操作两组查询结果,进行交集、并集、减集运算

1、 union和union all进行并集运算

–union 并集、不重复

select id, name from student where name like ‘ja%’

union

select id, name from student where id = 4;

–并集、重复

select * from student where name like ‘ja%’

union all

select * from student;

2、 intersect进行交集运算

–交集(相同部分)

select * from student where name like ‘ja%’

intersect

select * from student;

3、 except进行减集运算

–减集(除相同部分)

select * from student where name like ‘ja%’

except

select * from student where name like ‘jas%’;

公式表表达式

查询表的时候,有时候中间表需要重复使用,这些子查询被重复查询调用,不但效率低,而且可读性低,不利于理解。那么公式表表达式可以解决这个问题。

我们可以将公式表表达式(CET)视为临时结果集,在select、insert、update、delete或是create view语句的执行范围内进行定义。

–表达式

with statNum(id, num) as

(

select cid, count(*)

from student

where id > 0

group by cid

)

select id, num from statNum order by id;

with statNum(id, num) as

(

select cid, count(*)

from student

where id > 0

group by cid

)

select max(id), avg(num) from statNum;

连接查询

1、 简化连接查询

–简化联接查询

select s.id, s.name, c.id, c.name from student s, classes c where s.cid = c.id;

2、 left join左连接

–左连接

select s.id, s.name, c.id, c.name from student s left join classes c on s.cid = c.id;

3、 right join右连接

–右连接

select s.id, s.name, c.id, c.name from student s right join classes c on s.cid = c.id;

4、 inner join内连接

–内连接

select s.id, s.name, c.id, c.name from student s inner join classes c on s.cid = c.id;

–inner可以省略

select s.id, s.name, c.id, c.name from student s join classes c on s.cid = c.id;

5、 cross join交叉连接

–交叉联接查询,结果是一个笛卡儿乘积

select s.id, s.name, c.id, c.name from student s cross join classes c

–where s.cid = c.id;

6、 自连接(同一张表进行连接查询)

–自连接

select distinct s.* from student s, student s1 where s.id <> s1.id and s.sex = s1.sex;

函数

1、 聚合函数

max最大值、min最小值、count统计、avg平均值、sum求和、var求方差

select

max(age) max_age,

min(age) min_age,

count(age) count_age,

avg(age) avg_age,

sum(age) sum_age,

var(age) var_age

from student;

2、 日期时间函数

select dateAdd(day, 3, getDate());–加天

select dateAdd(year, 3, getDate());–加年

select dateAdd(hour, 3, getDate());–加小时

–返回跨两个指定日期的日期边界数和时间边界数

select dateDiff(day, ‘2011-06-20’, getDate());

–相差秒数

select dateDiff(second, ‘2011-06-22 11:00:00’, getDate());

–相差小时数

select dateDiff(hour, ‘2011-06-22 10:00:00’, getDate());

select dateName(month, getDate());–当前月份

select dateName(minute, getDate());–当前分钟

select dateName(weekday, getDate());–当前星期

select datePart(month, getDate());–当前月份

select datePart(weekday, getDate());–当前星期

select datePart(second, getDate());–当前秒数

select day(getDate());–返回当前日期天数

select day(‘2011-06-30’);–返回当前日期天数

select month(getDate());–返回当前日期月份

select month(‘2011-11-10’);

select year(getDate());–返回当前日期年份

select year(‘2010-11-10’);

select getDate();–当前系统日期

select getUTCDate();–utc日期

3、 数学函数

select pi();–PI函数

select rand(100), rand(50), rand(), rand();–随机数

select round(rand(), 3), round(rand(100), 5);–精确小数位

–精确位数,负数表示小数点前

select round(123.456, 2), round(254.124, -2);

select round(123.4567, 1, 2);

4、 元数据

select col_name(object_id(‘student’), 1);–返回列名

select col_name(object_id(‘student’), 2);

–该列数据类型长度

select col_length(‘student’, col_name(object_id(‘student’), 2));

–该列数据类型长度

select col_length(‘student’, col_name(object_id(‘student’), 1));

–返回类型名称、类型id

select type_name(type_id(‘varchar’)), type_id(‘varchar’);

–返回列类型长度

select columnProperty(object_id(‘student’), ‘name’, ‘PRECISION’);

–返回列所在索引位置

select columnProperty(object_id(‘student’), ‘sex’, ‘ColumnId’);

5、 字符串函数

select ascii(‘a’);–字符转换ascii值

select ascii(‘A’);

select char(97);–ascii值转换字符

select char(65);

select nchar(65);

select nchar(45231);

select nchar(32993);–unicode转换字符

select unicode(‘A’), unicode(‘中’);–返回unicode编码值

select soundex(‘hello’), soundex(‘world’), soundex(‘word’);

select patindex(’%a’, ‘ta’), patindex(’%ac%’, ‘jack’), patindex(‘dex%’, ‘dexjack’);–匹配字符索引

select ‘a’ + space(2) + ‘b’, ‘c’ + space(5) + ‘d’;–输出空格

select charIndex(‘o’, ‘hello world’);–查找索引

select charIndex(‘o’, ‘hello world’, 6);–查找索引

select quoteName(‘abc[]def’), quoteName(‘123]45’);

–精确数字

select str(123.456, 2), str(123.456, 3), str(123.456, 4);

select str(123.456, 9, 2), str(123.456, 9, 3), str(123.456, 6, 1), str(123.456, 9, 6);

select difference(‘hello’, ‘helloWorld’);–比较字符串相同

select difference(‘hello’, ‘world’);

select difference(‘hello’, ‘llo’);

select difference(‘hello’, ‘hel’);

select difference(‘hello’, ‘hello’);

select replace(‘abcedef’, ‘e’, ‘E’);–替换字符串

select stuff(‘hello world’, 3, 4, ‘ABC’);–指定位置替换字符串

select replicate(‘abc#’, 3);–重复字符串

select subString(‘abc’, 1, 1), subString(‘abc’, 1, 2), subString(‘hello Wrold’, 7, 5);–截取字符串

select len(‘abc’);–返回长度

select reverse(‘sqlServer’);–反转字符串

select left(‘leftString’, 4);–取左边字符串

select left(‘leftString’, 7);

select right(‘leftString’, 6);–取右边字符串

select right(‘leftString’, 3);

select lower(‘aBc’), lower(‘ABC’);–小写

select upper(‘aBc’), upper(‘abc’);–大写

–去掉左边空格

select ltrim(’ abc’), ltrim(’# abc#’), ltrim(’ abc’);

–去掉右边空格

select rtrim(’ abc ‘), rtrim(’# abc# '), rtrim(‘abc’);

6、 安全函数

select current_user;

select user;

select user_id(), user_id(‘dbo’), user_id(‘public’), user_id(‘guest’);

select user_name(), user_name(1), user_name(0), user_name(2);

select session_user;

select suser_id(‘sa’);

select suser_sid(), suser_sid(‘sa’), suser_sid(‘sysadmin’), suser_sid(‘serveradmin’);

select is_member(‘dbo’), is_member(‘public’);

select suser_name(), suser_name(1), suser_name(2), suser_name(3);

select suser_sname(), suser_sname(0x01), suser_sname(0x02), suser_sname(0x03);

select is_srvRoleMember(‘sysadmin’), is_srvRoleMember(‘serveradmin’);

select permissions(object_id(‘student’));

select system_user;

select schema_id(), schema_id(‘dbo’), schema_id(‘guest’);

select schema_name(), schema_name(1), schema_name(2), schema_name(3);

7、 系统函数

select app_name();–当前会话的应用程序名称

select cast(2011 as datetime), cast(‘10’ as money), cast(‘0’ as varbinary);–类型转换

select convert(datetime, ‘2011’);–类型转换

select coalesce(null, ‘a’), coalesce(‘123’, ‘a’);–返回其参数中第一个非空表达式

select collationProperty(‘Traditional_Spanish_CS_AS_KS_WS’, ‘CodePage’);

select current_timestamp;–当前时间戳

select current_user;

select isDate(getDate()), isDate(‘abc’), isNumeric(1), isNumeric(‘a’);

select dataLength(‘abc’);

select host_id();

select host_name();

select db_name();

select ident_current(‘student’), ident_current(‘classes’);–返回主键id的最大值

select ident_incr(‘student’), ident_incr(‘classes’);–id的增量值

select ident_seed(‘student’), ident_seed(‘classes’);

select @@identity;–最后一次自增的值

select identity(int, 1, 1) as id into tab from student;–将studeng表的烈属,以/1自增形式创建一个tab

select * from tab;

select @@rowcount;–影响行数

select @@cursor_rows;–返回连接上打开的游标的当前限定行的数目

select @@error;–T-SQL的错误号

select @@procid;

8、 配置函数

set datefirst 7;–设置每周的第一天,表示周日

select @@datefirst as ‘星期的第一天’, datepart(dw, getDate()) AS ‘今天是星期’;

select @@dbts;–返回当前数据库唯一时间戳

set language ‘Italian’;

select @@langId as ‘Language ID’;–返回语言id

select @@language as ‘Language Name’;–返回当前语言名称

select @@lock_timeout;–返回当前会话的当前锁定超时设置(毫秒)

select @@max_connections;–返回SQL Server 实例允许同时进行的最大用户连接数

select @@MAX_PRECISION AS ‘Max Precision’;–返回decimal 和numeric 数据类型所用的精度级别

select @@SERVERNAME;–SQL Server 的本地服务器的名称

select @@SERVICENAME;–服务名

select @@SPID;–当前会话进程id

select @@textSize;

select @@version;–当前数据库版本信息

9、 系统统计函数

select @@CONNECTIONS;–连接数

select @@PACK_RECEIVED;

select @@CPU_BUSY;

select @@PACK_SENT;

select @@TIMETICKS;

select @@IDLE;

select @@TOTAL_ERRORS;

select @@IO_BUSY;

select @@TOTAL_READ;–读取磁盘次数

select @@PACKET_ERRORS;–发生的网络数据包错误数

select @@TOTAL_WRITE;–sqlserver执行的磁盘写入次数

select patIndex(’%soft%’, ‘microsoft SqlServer’);

select patIndex(‘soft%’, ‘software SqlServer’);

select patIndex(’%soft’, ‘SqlServer microsoft’);

select patIndex(’%so_gr%’, ‘Jsonisprogram’);

10、 用户自定义函数

查看当前数据库所有函数

–查询所有已创建函数

select definition,* from sys.sql_modules m join sys.objects o on m.object_id = o.object_id

and type in(‘fn’, ‘if’, ‘tf’);

创建函数

if (object_id(‘fun_add’, ‘fn’) is not null)

drop function fun_add

go

create function fun_add(@num1 int, @num2 int)

returns int

with execute as caller

as

begin

declare @result int;

if (@num1 is null)

set @num1 = 0;

if (@num2 is null)

set @num2 = 0;

set @result = @num1 + @num2;

return @result;

end

go

调用函数

select dbo.fun_add(id, age) from student;

–自定义函数,字符串连接

if (object_id(‘fun_append’, ‘fn’) is not null)

drop function fun_append

go

create function fun_append(@args nvarchar(1024), @args2 nvarchar(1024))

returns nvarchar(2048)

as

begin

return @args + @args2;

end

go

select dbo.fun_append(name, ‘abc’) from student;

修改函数

alter function fun_append(@args nvarchar(1024), @args2 nvarchar(1024))

returns nvarchar(1024)

as

begin

declare @result varchar(1024);

–coalesce返回第一个不为null的值

set @args = coalesce(@args, ‘’);

set @args2 = coalesce(@args2, ‘’);;

set @result = @args + @args2;

return @result;

end

go

select dbo.fun_append(name, ‘#abc’) from student;

返回table类型函数

–返回table对象函数

select name, object_id, type from sys.objects where type in (‘fn’, ‘if’, ‘tf’) or type like ‘%f%’;

if (exists (select * from sys.objects where type in (‘fn’, ‘if’, ‘tf’) and name = ‘fun_find_stuRecord’))

drop function fun_find_stuRecord

go

create function fun_find_stuRecord(@id int)

returns table

as

return (select * from student where id = @id);

go

select * from dbo.fun_find_stuRecord(2);

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码