sql 分类及语句使用

转载地址:https://blog.csdn.net/gnf_cc/article/details/57074549

1.DDL 操作:数据定义语言,用来定义数据库对象
       关键字:create  alert  drop

2.DML 操作:数据操作语言,用来定义数据库的记录,对表中数据进行增删改操作
insert:语法:insert into 表名(列名1,列名2...)values(values1,values2...)
如果要使用空值,使用 null
update:update 表名 set 列名1 = value1,... where 条件
delete: delete from 表名 where 条件
补充:truncate 是直接把表删掉,然后再创建一个同样的新表,删除数据无法找回;
执行速度比 delete 快,delete 删除表中的读数据,表结构还在,数据也可找回。

3.DQL 操作:数据查询语言
 select selection_list    / 要查询的列名
 from table_list           / 要查询的表名
 where condition       / 要查询的条件
 group by    grouping_colunmns      / 对查询的条件进行分组
 having     condition   / 分组后的行条件
 order by sorting_colunmns   / 对结果进行排序
 limit offset_start,row_count   / 对结果进行限定

注意:条件查询
运算符和关键字:
  • =、!=、<>、 <、<=、>、>=
  • between… and
  • in(set)
  • is null
  • and
  • or
  • not
1>.查询性别非男的学生记录
  • select * from stu where gender !='male'
  • select * from stu where gender <> 'male'
  • select * from stu where not gender ='male'
2>.查询姓名不为 null 的学生记录:
  • select * from stu where sname is not NULL
  • select * from stu where not sname is NULL
字段控制查询:
  • 字段为空,查看 emp 表中的 月薪和奖金之和,因为 sal 和 comm 都是数值类型,可以直接进行 加运算,反之,会出错

    • select * ,sal+comm from emp
    • select *,sal+ IFNULL(comm,0) from emp
    • 如果我们要查询的 列 中 记录有 NULL ,那么使用 IFNULL 函数,把 NUL 转换为 默认数值,上面默认 为 0
  • 给列名添加 别名 : 我们可以给查询出来的列重新起名,使用 AS 关键字,也可以省略
    • select * ,sal + IFNULL(comm,0) as total from emp

聚合函数

sum,avg,max,min,count,聚合函数是用来做纵向运算的函数

  • count():统计指定列不为 NULL 的记录行数
  • max():计算指定列的最大值,如果指定的列是 字符串,那么使用字符串 排序运算
  • min():计算指定列的最小值
  • sum():计算指定列 的数值和,如果不是数值类型,那么 结果为 0
  • 统计月薪与奖金之和大于2500元的人数
    • select count(*) from emp where (sal+IFNULL(comm,0))>2500
  • 查询有奖金的人数,以及所有有领导的人数
    • select count(comm),count(mgr) from emp

分组查询

当需要分组查询时需要使用 group by 字句,凡是和 聚合函数同时出现的列名,要写在 group by 之后

分组查询

  • 查询每个部门的部门编号以及每个部门工资大于1500的人数
    • select deptno,count(*) from emp where sal >1500 group by deptno

having 子句

  • 查询工资总和大于9000的部门编号以及工资和
    • select deptno,sum(sal) from emp group by deptno having sum(sal)>9000

[having 和 where 的区别:having 是在分组之后对数据进行过滤,having 后面可以使用分组函数;where 是在分组之前对数据进行过滤,where 后面不可以使用分组函数;where 是对分组前记录的条件,如果记录不满足 where 的条件,那么该数据就不会参与分组,而 having 是对分组之后的数据进行 约束]

总结

查询语句 书写顺序 :select – from – where – group by – having – order by – limit
查询语句 执行顺序 :from – where – groub by – having – order by – limit


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值