MySQL之数据库的常用语句

Mysql数据库的常用语句

一、常用数据库的命令

1.show databases; 查看所有的数据库
2.create database test; 创建一个叫test的数据库
3.drop database test;删除一个叫test的数据库
4.use test;选中库 ,在建表之前必须要选择数据库
5.show tables; 在选中的数据库之中查看所有的表
6.create table 表名 (字段1 类型, 字段2 类型);
7.desc 表名;查看所在的表的字段
8.drop table 表名; 删除表
9.show create databases 库名;查看创建库的详细信息
10.show create table 表名; 查看创建表的详细信息

二、修改表的命令

1.修改字段类型 alter table 表名 modify 字段 字段类型;
2.添加新的字段 alter table 表名 add 字段 字段类型
3.添加字段并指定位置  alter table 表名 add 字段 字段类型   after 字段;
4.删除表字段  alter table 表名 drop 字段名;
5.修改指定的字段  alter table 表名 change 原字段名字  新的字段名字 字段类型

三、对字段的命令

1.增加数据(insert)3种方式 
    insert into 表名 values(值1,值2,...)(很少用)
    insert into 表名(字段1,字段2...) values(值1,值2,....);(较常用)
    insert into 表名(字段1,字段2...) values(值1,值2,....),(值1,值2,....),(值1,值2,....);
2.删除数据(delete) 
    delete from 表名 where 条件 注意:where 条件必须加,否则数据会被全部删除
3.更新数据(update) 
    update 表名 set字段1 = 值1, 字段2 = 值2 where 条件
3.筛选重复值的字段    
    select distinct 字段 from 表名  #注意:where 必须加,否则数据全部修改
4.查询数据(select)
    1.查询表中的所有数据   select * from 表名
    2.指定数据查询    select 字段 from 表名 
    3.集合 id [not] in(1,2)模糊查询  :like '%a%';
    4.根据条件查询出来的数据  select 字段 from 表名 where 条件 (最常用的)
where 条件后面跟的条件
    关系:>,<,>=,<=,!=  
    逻辑:or, and 
    区间:id between 4 and 6 ;闭区间,包含边界
5.结果集排序
    1, 通过字段来排序
    例如 :select * from star orser by money desc, age asc;                                                   6.限制结果集
select 字段 from 表 order by 字段  排序关键词(desc | asc)
排序关键词 desc 降序 asc 升序(默认)
    2, 多字段排序
    select 字段 from 表 order by 字段1  desc |asc,...字段n desc| asc;
    select  字段 from 表 limit 数量;
    例如:select sum(id) from star                                                                        8.分组
select * from 表名  limit 偏移量,数量
说明:
1.不写偏移量的话就是默认的为0
2.实现分页的时候必须写偏移量
  偏移量怎么计算?:
    limit (n-1)*数量 ,数量 
7.常用的统计函数
sum,avg,count,max,min
只分组:select * from 表 group by 字段
例子: select count(sex) as re,sex from star group by sex having re > 3;
分组统计: select count(sex) from star group by sex;
分组后结果集的过滤

猜你喜欢

转载自www.cnblogs.com/Yedada/p/10263449.html