读书笔记--MySQL(1)

来源:互联网 发布:朱雀网络和小米的关系 编辑:程序博客网 时间:2024/06/06 20:56

sql基础:

1)显示有几个数据库

show databases;

2)创建一个数据库

create database dbname;

3)删除一个数据库

drop database dbname;

4)使用数据库

use dbname;

5)展示数据库dbname下有哪些表

show tables;

6)在数据库dbname下创建表tbname

create table tbname(

id int(4) not null auto_increment primary_key,

name varchar(20),

country varchar(50) default 'CN' 

)engine=InnoDB default charset=utf8;

7)显示表属性

desc tbname;

8)显示建表语句

show create table tbname;

9)删除表

drop table tbname;

10)表增加一列age,int不写长度的话,默认是int(11),一下两句效果一样,可以省略column

alter table tbname add age int(3);

alter table tbname add column age int(3);

11)修改表中列的属性

alter table tbname modify name varchar(200);

12)  删除表中的列

alter table tbname drop age1;

13)修改表字段age为age2,且属性改为int(4)

修改表字段名称,同时也可以改类型,功能比modify强大

alter table tbname change age age2 int(4);

14)添加表字段birthday 在字段name后面;若没有则默认添加的字段在末尾

alter table tbname add birthday date after name;

添加表字段index在最前面:

alter table tbname add index int(1) first;

15)修改表名称

alter table tbname rename tbname1;

16)插入数据:

表名称后面不带字段时,默认按表字段属性全部插入;若带了表字段,则按顺序依次插入

insert into tbname values ('','','');

insert into tbname(name,age) values('lilalla',100);

17)查询数据

order by:排序    desc:降序  asc:升序

select * from tbname order by name desc,age asc;

18)分页查询:

语法:limit offset_start,row_count

limit 0,3 从第一条记录开始的三条记录(前三条记录),若从0开始,则可简写成:limit 3

limit 1,3 从第二条记录开始的三条记录

select * from tbname limit 0,3;

19)聚合函数:

常用的聚合函数有:sum,count,max,min

count(0),count(1),count(*)   均是查有多少天记录

count(expr)则是查询满足表达式expr的有多少条记录

语法:

select [field1,field2]  count(1) from tbname   [where    .....]

[group by field1,field2]

[with rollup]

[having .......] 

group by :表示分类聚合的字段,select时有几个属性必须在group by中写几个属性,聚合函数除外

where :对分类前进行过滤

having:对分类后的结果进行过滤

rollup:对分类聚合的结果再汇总

举例:

统计总人数:select count(*) from emp;

统计个部门人数:select deptno,count(1) from emp group by deptno;

统计人数大于1的部门:select deptno ,count(1) from emp group by deptno having count(1)>1;

统计各部门人数,也要统计总人数:select deptno,count(1) from emp group by deptno rollup;

20)表连接

表连接分为:内连接和外连接

内连接:仅仅选出两张表中相互匹配的记录;外连接:会选出其它不匹配的记录

外连接又分:左连接和右连接

左连接:包含左表中的所有记录,甚至是右表中没有与之相匹配的记录,以左表字段为准;

右连接:包含右表中的所有记录,甚至是左表中没有与之相匹配的记录,以右表字段为准;

举例:

内连接:select ename,deptname from emp,dept where emp.deptno=dept.deptno;

左外连接:select ename,deptname from emp left join dept on emp.deptno=dept.deptno;

21)子查询

关键字有:in,not in,=,!=,exists,not exists

select * from emp where deptno in (select deptno from dept)

若deptno唯一可以用=替换in

各种子查询大部分条件下可以变换成表连接

上例子可编程:select * from emp,dept where dept.deptno=emp.deptno;

22)记录联合:

关键字:union/union all

union:将结果集合并;union all:将结果集合并后去重

select deptno from emp union all select deptno from dept;

0 0
原创粉丝点击