关于SQL

zz1.SQL(结构化查询语言)
1.1分类
DML(数据操作语言):
insert(增加),update(修改),delete(删除)

DCL(数据控制语言):
grant(授权),revoke(取消授权)

DQL(数据查询语言):
select(查询)

DOL(数据定义语言):
create(创造表),drop(删除表),truncat(截断表)


1.2DML
a.insert(增加)
语法:insert into 表名(列名...)values(值..);
列:insert into student(id,name,addr)values(11,"张三","上海")
注意:1)列名数和指数要保持一致。
2)主键列不能重复
3)不能插入null值

b.delete(删除)
语法:delete from 表明 where 条件;
列:delete from studenthere where id=1;

注意:如果没有where条件,那么delete from 表明;
删除表的所有记录.

c.update(修改)
语法:update 表明 set 列名=值,列名2=值.....
where 条件.

1.3DDL
a.create table(创建表)
create table 表明(列名 类型...);
列:
create table stu(id bigint name varchar(20));


b.truncate table(截断表)
语法:truncate table 表明;(删除表中的所有记录)
列:truncate table stu;


c.drop table(删除表)
语法:drop table 表名
列:drop table 表明;

1.4DQL(数据查询语言)
a.语法:
select 列名,....
from 表明
where 条件表达式
order by 列名
列:select empno ename,sal from emp where empno=7788 order by empno


b.别名 as
语法: 列名 as 列别名.
列:select ename as '姓名',sal as '工资' from emp;


c.运算:
1)比较运算符
>,<,>=,<=,<>.
2)逻辑运算符
and:与
or:或
not:非

列:查询员工工资大于3000或者入职日期早于1900年的员工姓名和工资,入职日期. not
select ename,sal,hiredate form emp where sal>3000or hiredate<'1900'

3)is null is not null;
is null 表示为空
is not null表示不为空

d)常量查询
select ename,sal,'城市学院' as '学校' from emp;


e)固定行/按比例查询
列:select top 5 ename,sal from emp;
select top 50 percent ename,sal from emp;

f)排序 order by 列名,列名...asc/desc
desc 表示:降序
asc 表示:升序(默认值)

1.5 模糊语句 like
语法:select 列名 from 表名 where 列名 like '占位符号或者字符占位符'
%:0个或者多个以上;
[]:表示范围内 列:[1-2]
[]:表示不在范围内的任意一个[^1-2]
列:查询员工中,员工姓名包含M的员工姓名和员工编号
select empno,ename from emp where ename like '%m%';

1.6 between ....and .... 在...和...之间.
列:select ename,sal,comm form emp where sal between 100 and 1000;


1.7 in 表示括号内的任意一个
列:select ename,deptno form emp where deteno in (10,20);

1.8sum:求和 avg:平均值 max:平均值 min:最小值 count:记录数
select SUM(SAL) from EMP;

select avg(SAL) from EMP;

select max(SAL) from EMP;

select min(SAL) from EMP;

select count(*) from EMP;

注意:count是不记录null的。


1.9分组查询(group by)
语法: select .... 5
from .... 1
where..... 2
group by 3
having .... 4 --分组过滤
order by... 6

注意:如果包含group by的sql那么在select后面只能接被分组的列和聚合函数

where:用来筛选from子句中制定的操作算产生的行


2.多表链接(就是把多个表变成一个表再去操作)
2.1 内连接(inner join)
select .....
from 表1 inner join 表2 on 链接条件
where ....
.....
.....
链接过程:拿表1的每一条数据与表2的每一条数据根据链接条件去匹配,
如果匹配到记录,则把这条匹配的数据放到新的结果集中.
如果匹配不到记录,不放入结果集中,并且进行下一条的匹配.

等价于:
select ....from 表1,表2 where 连接条件

列:求员工的薪资等级
--非等值条件
select e.ENAME,s.GRADE from EMP e,SALGRADE s where e.SAL between s.LOSAL and s.HISAL;


2.2左|右外连接(主表的区别)
语法:select * from 表1 left join 表2 on 连接条件
语法:select * from 表1 right join 表2 on 连接条件
连接过程:拿着主表(左外连接就是左边表,右外连接就是右边表)
每一条记录与从表的每一条记录按连接条件匹配,
如果匹配到记录则把记录组合放到结果集中,
如果朱彪的记录在从表中没有匹配到记录,则主表的记录,
也会放入结果集中并且从表的记录的列的值是null.

原文地址:https://www.cnblogs.com/zhousha929-/p/6866748.html