当前位置: 移动技术网 > IT编程>开发语言>Java > mysql语法总结及例子

mysql语法总结及例子

2019年11月02日  | 移动技术网IT编程  | 我要评论

1. ddl相关

 a.

-- 查询所有数据库
show databases;
-- 删除数据库
drop database ladeng;

 b.

-- use `数据库名称`;  表示使用此数据库
use ladeng;

 c.

-- 查看表结构
show create table student;

d.  往表中添加新字段

alter table `report_user_manage` add is_delete tinyint(2) not null comment '是否删除 0-未删除 1-已删除';
alter table `report_user_manage` add creator varchar(50) not null comment '创建人';
alter table `report_user_manage` add gmt_create datetime not null comment '创建时间';
-- 当数据新插入时更新时间默认为null, 当数据修改时更新时间会自动变化
alter table `report_user_manage` add gmt_modified datetime default null on update current_timestamp comment '更新时间';

e

-- 如果源字段值是其它类型如:vachar且有值, 修改为新字段bigint类型,则会报报,需要先清空这个字段值才能修改字段名称; 如果源字段值都为null或者类型也为bigint则直接修改不会报错
alter table 表名 change  `源字段名称` `目标字段名称`  bigint(20)  default null comment '逾期已还用户数';

2. 查询表总共有多少条数据, 一般有如下3中写法,  推荐优先使用 count(1) 或 count(id) 

-- count(1):性能高
select count(1) from student;
-- count(带索引的字段):性能高, count(未带索引的字段):性能一般, count(字段)时需要注意,如果该字段值存在有null则统计有误差.
select count(字段名称) from student; 如: select count(id) from student; -- count(*): * 会扫描所有列,故性能比前面几种低 select count(*) from student;

 3. 单条插入

-- 如果选中了数据库则数据库名称可以省略; 
-- 如果数据库名称或表名称是中文名或者字段名称是关键字,则尽量加上 `` 包裹起来
-- 如果id是自增,则id默认一般不能插入,除非自己修改数据库配置允许插入id;
-- 所有字段值都可以用单引号包围, 如果字段类型不是varchar类型,也能使用''包裹字段值, 底层做了类型强制转换成varchar insert into 数据库名称.表名称 (字段名称1, 字段名称2) values('字段1值', '字段2值'); insert into `ladeng`.`student` (`name`, `age`, `score`, `courseid`) values ('小明', '19', '100', '3');

 4. 批量插入(插入条数100条至10000条以内性能高, 具体插入条数看插入的字段个数和字段值的字符数, 推荐1000条)

--  方式一(多条插入语句中间用分号; 分隔): 如: 下面这2条同时执行
insert into `ladeng`.`student` (`name`, `age`, `score`, `courseid`) values ('小红', '18', '15', '3');
insert into `ladeng`.`student` (`name`, `age`, `score`, `courseid`) values ('小丽', '22', '25', '3');

-- 方式二: values后面跟多条数据,中间用顿号、分隔
insert into `ladeng`.`student` (`name`, `age`, `score`, `courseid`) values ('小红', '18', '15', '3'),('小丽', '22', '25', '3');

 5. 单条更新语句

update `ladeng`.`student` set `score`='79', age = 19  where `id` = '1';

6. 批量更新语句: 参照批量插入的第一种方式

7.  删除语句

delete from student where id in (14, 15);

 8.  between ... and ... 在什么之间, 如: 查询年龄>= 19并且年龄<=22数据

select * from student where age between 19 and 22  等价于
select * from student where age >=19 and age <= 22 

9. 聚焦函数(count, sum, max, min, group by), 将多行数据聚焦成一个值

-- 查询总条数, 如果不存在id>2的数据则count(1)会返回0,而不是返回null
select count(1) from student where id > 2
-- 查询所有学生所有科目总分数, 如果表中没有数据则sum(score)会返回null,而不是返回0
select sum(score) from student 
-- 查询所有学生所有科目总分数, 如果没有数据就默认返回0; ifnull是用来判断是否为空,为空则赋值一个默认值
select ifnull(sum(score), 0) from student
-- 查询每个学生所有科目分数, 按照学生名字分组; group by 作用是分组,如果需要对多个字段分组,则 group by 字段1,字段2,...
select `name`, sum(score) from student group by `name`;

 

 

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网