sql基础

Sql

1.       group by 及 order by 区别

默认 升序 asc

order by task.name,task.test desc

2.       内联接,外联接区别?.

外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。

内连接:A,B的所有行都需要满足连接条件on

左连接:左边表中id在右边表中不存在时,右边补null;右连接与左连接相反

取A所有数据,on条件中B没有的数据补null

A、left outer join:

左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。

select a.a, a.b, a.c, b.c, b.d, b.f

from a

LEFT OUT JOIN b

ON a.a = b.c

Where a.a=1

B:right outer join:

右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。

3.       显示前10行数据

  oracle:

  select * from tab where rownum <=10

  sqlserver:

  select top 10 * from tab

  mysql:

  select * from tab limit 10

4.       清除表

drop table  tb   表和数据一起清除

truncate table tb 清除里面所有数据,释放空间-ID重新为0

delete table tb清除里面所有数据,不释放空间。速度慢,一行一行来

5.       模糊查询

%% :找出  丽丽三爸爸

_三 : 找出张三,李三。。。。

[ 1-9] :找出1-9

[^1-9 ] :找不出1-9

7. Having与Where的区别

where 子句的作用是在对查询结果进行分组前,将不符合where条件的行去掉,即在分组之前过滤数据,where条件中不能包含聚组函数,使用where条件过滤出特定的行。

having 子句的作用是筛选满足条件的组,即在分组之后过滤数据,条件中经常包含聚组函数,使用having 条件过滤出特定的组,也可以使用多个分组标准进行分组。

select 类别, sum(数量) as 数量之和 from A

group by 类别

having sum(数量) > 18

8. 常用语句

增加一列:Alter table tabname add column col type

插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 范围
更新:update table1 set field1=value1 where 范围
查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,

date –d@+时间格式

9、说明:选择从10到15的记录

从子查询里选15条,排倒序后再选5条

select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc

子查询  = 单子查询  in 多子查询 hash 连接  exist  loop循环

1、  单行子查询

        select ename,deptno,sal

        from emp

        where deptno=(select deptno from dept where loc='NEW YORK');

     2、多行子查询

        SELECT ename,job,sal

        FROM EMP

        WHERE deptno in ( SELECT deptno FROM dept WHERE dname LIKE 'A%');

     3、多列子查询

        SELECT deptno,ename,job,sal

        FROM EMP

        WHERE (deptno,sal) IN (SELECT deptno,MAX(sal) FROM EMP GROUP BY deptno);

     4、内联视图子查询

       (1)SELECT ename,job,sal,rownum

          FROM (SELECT ename,job,sal FROM EMP ORDER BY sal);

       (2)SELECT ename,job,sal,rownum

          FROM ( SELECT ename,job,sal FROM EMP ORDER BY sal)

          WHERE rownum<=5;

     5、在HAVING子句中使用子查询

        SELECT deptno,job,AVG(sal) FROM EMP GROUP BY deptno,job HAVING AVG(sal)>(SELECT sal FROM EMP WHERE ename='MARTIN');

原文地址:https://www.cnblogs.com/season-xie/p/5330968.html