当前位置:文档之家› 常用数据库sql语句写法整理

常用数据库sql语句写法整理

常用数据库知识复习
--创建一个用户表
create table users (id int(10),pwd char(20),name varchar(10));
char表示占20个长度的空间 varchar根据实际长度决定空间大小
--复制表
create table users_copy as select * from users;
--增加数据到表中
方式1:insert into users values(1,'1234','d1');
方式2:insert into users (id,name)values(2,'d2');
--查询数据
最简单的 select * from users;
条件查询 select * from users where id=1 ;
select * from users where id=1 and name='d1' ;(and表示且的意思)
select * from users where id=1 or id=2 ;(or表示或的意思)
select * from users where id in(1,3,4);(or的条件多了,用in)
select * from users where id>=2;(可以有大小条件)
select count(*) from users;(查询有多少条数)
select * from employ where name like '%duan%';(模糊查询)
select * from employ where name like 'duan%';(模糊查询,表示以duan开头---结尾反之)
select distinct name from users;(除去重复记录)
select * from employ order by id;(由小到大)
select * from employ order by id desc;(反之顺序排列)
查询的时候可以计算
select name,salary salary*12 from employ;(员工的年薪)
select name,salary+bonus from employ;(员工的月薪)
分组查询
select job, count(*)from emp_ning group by job;
过滤分组结果:having短语
select deptno, count(*)from emp_ning group by deptno having count(*) >= 5;
子查询(即用某一查询语句代替语句中要写的数据)
select name from emp_ning where salary > (select salary
from emp_ning where id = 1002);
--子查询的结果集是多行多列(结果如果返回多行,使用in, >all, >any, select name, salary, deptno from emp_ning
where (deptno, salary) in(select deptno, max(salary)from emp_ning group by deptno);
--子查询的结果如果返回一行( 使用单行比较运算符(=, >, <, <=, >=) )
select name, deptno, salary from emp_ning
where (deptno, salary) =(select deptno, max(salary)from emp_ning where deptno = 10
group by deptno);
关联查询
等值连接:(自连接为特殊情况)
内连接:
select https://www.doczj.com/doc/ed13639443.html,,dept.dname from emp join dept on emp.deptno =dept.deptno;
外连接:(若为left 表示左边的为驱动表(会全部显示) 右边的为匹配表 反之....)
外连接的结果集 = 内连接的结果集 + 驱动表中在匹配表中找不到匹配记录的 数据和空值的组合
select https://www.doczj.com/doc/ed13639443.html,, d.dname from emp_ning e left outer join dept_ning d on e.deptno = d.deptno;(emp的全部)
select https://www.doczj.com/doc/ed13639443.html,, d.dname from emp_ning e lright outer join dept_ning d on e.deptno = d.deptno;(dept的全部)
非等值连接:
select https://www.doczj.com/doc/ed13639443.html,,s.salary from emp e join salary s on e.sa

lary between s.lowsal and s.highsal;

查询的总格式:
select 表1.列1, 表1.列2, 表2.列1,表2.列2,....[组函数][单行函数]
from 表1
[left|right|full outer join 表2
on 表1.列1 = 表2.列2
where 条件1 and 条件2[子查询] or 条件3
group by 列
having 组函数的条件[子查询]
order by 列]


--更新数据的语句
update users set pwd='1234' where id=2;
--删除某行
delete from t_user where user_id = 1;
--删除表结构 drop table users;

SQL语句中的函数( mysql为例子)
select *,round(salary*2.12222222,4) from employ;(round函数,省略到小数点后4位的全部信息)
select now();(查询当前时间)
组函数 count / max / min / sum / avg



oracle数据库中的分页
select * from (select user_id,psort_id,user_name,user_age,insert_time,rownum as num from tb_user )t where num between ? and ?
?表示他们从第几位到第几位(非下标)
mysql中的分页
select * from d_book limit 0,5;
表示从下标为0的开始,每页五条


在mysql中 setnames utf8 可以解决查看数据库时乱码问题



相关主题
文本预览
相关文档 最新文档