天天看点

MYSQL数据库基础操作语句

新建数据库

create database 数据库名;

删除数据库

drop database 数据库名;

新建表

create table 表名 (

    表结构...

)

删除表

drop table 表名;        (无法找回)

删除表中所有数据

truncate 表名;            (删除表中所有数据)

查询表类型

desc 表名;

查看表结构

show create table 表名;

查询表

select * from 表名;

结构化查询数据    

select * from 表名\G;

cmd中文乱码解决

set charact_set_results = gbk;

给表添加字段

alter table 表名 add 字段名    字段类型(int,varchar,...);

给表删除字段

alter table 表名 drop 字段名;

修改表名(更改表名)

rename table 旧表名 to 新表名;

查询语句

!=     不等于

<>    不等于

=    等于

>    大于

<    小于

and    和

or    或

搜索id=5的数据

select * from 表名 where id = 5;

搜索id=5且name='李四'的数据

select * from 表名 where id = 5 and name = '李四';

搜索id>14

select *from 表名 where age > 14;

模糊查询,由3个字母组成,并且最后一位是 s

select * from 表名 where name like '__s';    // _匹配任意一个字节,

模糊查询,以 m 开头的任意字符串

select * from 表名 where name like 'm%';    //        %匹配0~n个字节

模糊查询,包含 见 的字符串

select * from 表名 where name like '%见%';

新增数据

insert into 表名 (字段名,...) values (字段值,...);        //    注意字段值与字段名一一对应

删除表中指定行

delete from 表名 where 条件    

去重查询

select distinct 字段名 from 表名;

排序查询 ,order by默认从小到大

select * from 表名 order by 字段名 ASC;        升序

select * from 表名 order by 字段名 DESC;    降序

查询数据数量

select count(*) from 表名;        // 不统计不为null的数据

统计查询

select SUM(字段名)    from  表名;    

查询该字段的平均值

select SVG(字段名)  from  表名;

查询峰值

select MAX(字段名),MIN(字段名)    from 表名;

分组查询

select * from 表名 GROUP BY    字段名;    // 注意GROUP BY单独使用时,只返回每组的第一条数据

将该字段下相同的分为一组,例如:在一家公司内的员工隶属于不同部门,

该部门下有 =>人事部,财务部,保安部,研发部,市场部

select 字段名1 from 表名 GROUP BY 字段名1;

搜索字段名1下的每组成员 

select 字段名1,GROUP_CONCAT('字段名2') from 表名 GROUP BY 字段名1;

查询语句注意

group by后面不能接where,where在group by前面,这里介绍having,专属于group by使用,功能与where一样

select = >  from = > where = > GROUP by = >having = > Order by = > limit

查询 条件 分组 条件 排序 分页

继续阅读