mysql基本语法大全

来源:互联网 发布:mac pr防抖cc2017 编辑:程序博客网 时间:2024/04/29 03:57

1 create database test1

2 show databases;

3 use test1;

4 show tables;

5 drop database test1;

6 create table emp(ename varchar(10),hiredate date,deptno int(2));

7 desc emp;//查看表的结构

8 show create table emp;//查看创建表的sql语句

9 drop table emp; //删除表的结构,既删除表

更新表的结构

10 alter table emp modify ename varchar(20);

11 alter table emp add column age int(3);

12 alter table emp drop column age;

13 alter table emp change age age1 int(4);

14 alter table emp add birth date after ename;

15 alter table emp modify age1(3) first;

16 alter table emp rename emp1;


16.1 alter table table_test drop primary key; 删除主键

16.2 alter table table_test add primary key(id); 增加主键

 插入

17 insert into emp(ename,age,id) values("jia",21,1);

18 insert into emp values("lilei",32,2);

19 insert into emp(ename,id) values("zhang",3)//没写的默认为NULL

20 insert into emp(ename,id) values("masi",4),("jia",5)//可以插入很多记录,提高效率

更新表的内容

21 update emp set age=25 where ename="jia" 

22 update emp a,dept b set a.age=a.age-b.age,b.name=a.ename where a.id=b.id;

删除表的记录

23 delete from emp where id=5;

24 delete a,b from emp a,dept b where a.id=b.id and a.id=1;//同时删除a b记录中为1的

25 delete from dept //删除表的所有记录,结构还在

查询

26 select distinct id from emp;//不重复的

27 select * from emp order by id//按照id排列 默认升序

28 select * from emp order by id desc;// 降序

29  select * from emp order by id desc,age asc;// id降序 对于id相同的age升序

30 select * from emp limit 3//显示前三条记录

31 select * from emp limit 1,3//从第二条记录,显示三条记录,0对于第一条,1对应第二条

聚合

select sum(id) from emp;//统计id的所有和

select count(1) from emp;//统计记录数

select id,count(id) from emp group by id;//统计相同id的记录数 

select id,count(id) from emp group by id with rollup;//统计相同id的记录数 ,并统计最后总记录数

select id,count(id) from emp group by id having count(id)>1;//统计相同id的记录数,并且记录数大于1

where和having区别

having是对聚合后的结果进行条件过滤,where在聚合前就对结果过滤,所以尽量先where,再having

内连接

内连接也叫连接,是最早的一种连接。还可以被称为普通连接或者自然连接内连接是从结果表中删除与其他被连接表中没有匹配行的所有行,所以内连接可能会丢失信息。

select emp.ename,dept.dname from emp,dept where emp.id=dept.id//只会列出共有的记录

外连接

左连接:包含所有的左边表中的记录甚至是右边表中没有的记录。

右连接:包含所有的右边表中的记录甚至是左边表中没有的记录。

select emp.ename,dept dname from emp left join dept on emp.id=dept.id

左连接可以转换为右连接select emp.ename,dept dname from dept right join emp on dept.id=emp.id

子查询

select * from emp where id in(select id from dept);

转换为表连接 select emp.* from emp,dept where emp.id=dept.id;

记录联合

查询完两个表后,把两个表的结果从上到下合并在一起显示出来,查询后的两个表的列数要相同

select id from emp

union all

select id from dept;//所有的都显示 union 去除重复的

特殊SQL语句

一个表中有个字段是ID 为整形数字,为一串数字,怎么找出不连续的记录 

select id from (select id from rt_issue order by id asc) t where not exists (select 1 from rt_issue where id=t.id-1)


0 0
原创粉丝点击