常用数据库查询语句「建议收藏」

常用数据库查询语句「建议收藏」常用数据库查询语句基本查询select字段1,字段2,…from表名;例如:selectid,namefromstu;条件查询select字段1,字段2,…from表名where字段关系符号值;关系符号<=>=<=!=大于等于大于等于小于等于不等于例如:select*fromstuid>2;andorin(范围内满足in内部条件)

大家好,欢迎来到IT知识分享网。

数据库常用查询语句(DQL)

基本查询

select 字段1, 字段2,…from 表名;

例如:select id , name from stu;

条件查询

select 字段1, 字段2,…from 表名 where 字段 关系符号 值 ;

关系符号

< = >= <= != 大于 等于 大于等于 小于等于 不等于

例如:select * from stu id > 2;

and or in(范围内满足in内部条件) not in 相反

例如: select * from stu where id>1 and age <40;

​ select * from stu where id >1 or name =‘张三’;

​ select * from stu where id in(3,4);

between 值1 and 值2 在[值1,值2]之间 包含两边临界值

例如: select * from stu where id between 2 and 4;

模糊查询

select * from 表名 where 字段 like ‘%值%’;

例如: select * from stu where name like ‘陈%’;

注: %的位置不同 表达的意思不同 陈% : 陈某某 ,%陈% : 某陈某,%陈:某某陈

% 匹配任意字符 (%可以是任意长度)_匹配指定长度字符 一个_代表一个长度

排序查询

select * from 表名 order by 字段 排序类型 asc 升序 desc 降序 没写排序类型 默认 升序

例: select * from stu order by id desc ;

聚合函数 多行数据一行返回

count(字段) 计数 计算该列不为空的数据个数

例 :select count(name) from stu;

sum(字段) 求和 计算该列所有数字的和 字符串求和结果为0

例:select sum(age) from stu;

max(字段) 最大值 获取该列最大值

例: select max(age) from stu;

min(字段) 最小值 获取该列最小值

例: select min(age) from stu;

avg(字段) 平均值 不为null的进行平均

例: select avg(age) from stu;

注:聚合函数要放在select 和 from 之间

去重

distinct(列) 一般配合count()一起使用

例;:select count(distinct 字段名) from stu;

分组查询

group by

例:select * from stu group by 字段名

流程控制函数

if(expr1,expr2,expr3)

​ 如果 expr1 为真 则返回expr2, 否则返回expr3

​ is null() 函数 判断为空

​ is null(字段) 如果是null 返回1 不是返回0

例:select id name if(isnull(score)=1,‘缺考’,score)from stu;

case

when 条件 then 执行语句

when 条件 then 执行语句

else 执行语句

end

执行第一个when后的条件,如果为true,执行then后的语句,

如果when后的条件为false,执行第二个when后的条件

如果都为flase 执行else后的语句

多表联查

1 联合查询-合并结果集

union 将两表的查询结果纵向连接(会去重)

union all 纵向拼接会保留全部

2 连接查询

将多个表多行数据相乘(笛卡尔积).

一对一: 在任何一张表添加字段均可

一对多:只能在多的表添加字段

多对多:定义中间表

连接方式:

内连接: select * from 表1 inner join 表2 on 关联条件(过滤条件);

​ 简写: select * from 表1,表2 where 表1.字段名 = 表2.字段名;

注:只会保留完全符合关联条件的数据

外连接: select * from

​ 左外连接: select * from 表1 left [outer] join 表2 on 表1.字段名 = 表2.字段名

​ 注:会保留左表中不符合条件的数据

​ 右外连接: select * from 表1 right [outer] join 表2 on 表1.字段名 = 表2.字段名

​ 注:会保留右表中不符合条件的数据

​ 注:会保留不满足条件的数据

子查询

子查询就是嵌套查询.

一般子查询出现在:

​ from后 : 当做一张表使用

​ where后: 当做条件使用

​ select 后

自连接:

自己连接自己

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/7504.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信