sql常用语句

来源:互联网 发布:杜兰特技术特点知乎 编辑:程序博客网 时间:2024/06/05 20:53
SQL
sql是一种声明性语言,是为计算机声明了一个我想从原始数据中获得什么样的结果的一个范例,简单的说就是计算机会根据SQL声明内容来从数据库中挑选符合声明的数据。
SQL语句执行顺序和语句顺序不一致。
SQL语法顺序
select
from
where
group by
having
union
order by
执行顺序
from
where
group by
having
select
distinct
union
order by






修改语句
insert into test(username,password)values("张三","123456");  插入
update  test set password="123pwd";                          修改语句,修改所有password为123pwd
update  test set password="334455",flag=222 where userId=5   修改userId为5的的password改为334455,flag改为222
update  test set password="334455",flag=222 where userId=5 and sex=0; 修改userId为5,性别为0的password改为334455,flag改为222
delete from test where userId =1                             删除test表中的userId为1的数据
alter table emp add column me int;                           向emp表中添加一列int类型的me列
alter table emp drop column me;                             向emp表中删除me列


查询语句
DESC emp;                                   查询emp表中所有表结构
select empno,ename,job,sal from emp        查询指定列


select * from test                         查询test表中的所有数据,*号表示查询表中所有数据
select * from test where userId=2          查询test表中 userID为2的所有数据
select username from test where userId=2   查询test表中userId为2的username
select username (as)用户名,sex (as)性别 from test where userId=2   查询test表中userId为2的username,sex,并为其起别名在查询中显示
select DISTINCT  username from  test       只显示结果不同的项(不会删除表内数据)




like查询
select * from emp where ename like '%s%'   模糊查询带emp表中ename中带有s的数据,其中%表示占用更零个或多个字符,如SMITH,MISS
select * from emp where ename like '_d%'   其中_表示占用了一个字符,如查询结果Mdth。
select * from emp where ename like '__d_%' 再入这段,表示模糊查询第三位为d,且d不能作为结束字段的字符串




is null 和=null的区别
IS NULL是判断某个字段是否为空,为空并不等价于为空字符串或为数字0;  

而 =NULL 是判断某个值是否等于 NULL,NULL = NULL和NULL <> NULL都为 FALSE。


select * from test where password is null;                      查询test表中password为null的所有列
selext * from test where password is not null;                  查询test表中password不为null的所有列
select * from test where userId>2 and userId<8;             select * from test where userId between 2 and 8; 
select * from test where userId in(1,3,5,7,9)
select * from test where userId = 1 or userId=3 or userID=5;
select * from test where userId not in(1,3,5,7);
select * from test order by userId asc;
select * from test order by userId desc;




常用函数
select lower(ename) from emp;
select upper(lower(ename)) from emp;
select count(*),avg(sal),max(sal) from emp;
select count()*
       主函数    我们学校的名字叫张三
       所有主函数需要查询再使用
如s
select * from emp where sal>(select avg(sal)from emp)
select deptno,count(*) from emp group beptno having deptno>10  


select e.ename,d.dname,d.deptno from emp e,