0
点赞
收藏
分享

微信扫一扫

MySQL基本操作3

小北的爹 2022-03-21 阅读 54
mysql

单表操作

3.1 数据操作

3.1.1 复制表结构和数据

1.复制已有的表结构

create temporary table 表名 like 旧表名; (只复制一份相同的表结构,但是不会复制表中保存的数据)

2.复制已有的表数据

insert into 表名2 select * from 表名1;

临时表:只能在当前会话使用,当前会话关闭,临时表删除,临时表不能用show tables;查看,也不能用rename to改名

3.1.2 解决主键冲突

1.主键冲突更新

若插入的数据出现了主键冲突,则插入的数据操作利用更新的方式实现

insert into 表名 values()  on duplicate key update 字段名=值;

例:

create table my_goods

(id int primary key,

name varchar(255),

content varchar(255),

keyword varchar(255)

)charset utf8;

insert into my_goods values (1,'橡皮','修改书写错误','文具'),(2,'铅笔','写字','文具');

select * from my_goods;

insert into my_goods values(1,'橡皮','修改书写错误','文具') on duplicate key update name='橡皮擦';

2.主键冲突替换(当发生主键冲突时,先删除此条记录,再重新插入)

replace into my_goods values(1,'橡皮','修改书写错误','文具');

3.1.3 清空数据

truncate table 表名;(清空表中的所有数据)

3.1.4 去除重复记录

select distinct 字段列表 from 表名;

3.2 排序与限量

3.2.1 排序

1.单字段排序

select (字段列表) from 表名 order by 字段名 [desc|asc];

2.多字段排序

select (字段名) from 表名 order by 字段名1 asc,字段名2 desc;#先按字段名1升序排序,再按照字段名2降序排列

值得一提的是:在按照指定字段进行升序排列时,如果某条记录的字段为NULL,系统会将NULL看做是最小值。

3.2.2 限量

select (字段列表) from 表名 order by 字段名 [desc|asc]  limit [offset,] 记录数;

3.3 分组与聚合函数

3.3.1 分组

1.分组统计

在MySQL中,可以使用 group by 根据一个字段或多个字段进行分组,字段值 相同的为一组,对于分组的数据可以用 having进行条件筛选

select * from 表名 where  group by 字段名;

2.分组排序

select * from 表名 where group by 字段名 desc | asc;

3.多分组统计

4.回溯统计

select * from 表名 where group by 字段名 asc | desc ,... with rollup;

注意:回溯统计和排序只能出现一个

5.统计筛选 select * from 表名 where 条件 group by 字段名  having 条件;

5.3.2 聚合函数

select count(*) from goods where price<1000;

select sum(price) from goods where price>1000;

select avg(price) from goods;

select id from goods order by price desc limit 1;

3.4 运算符

3.4.1 算术运算符

select 2+5;

select '2'+'5';

select 5/2,5%2;

返回33到57的随机数[33,57]  select floor(33+rand()*24);

5.4.2 比较运算符

between ...and

not between and

is null

is not null

like '匹配模式'

not like 

 比较函数

in()

not in()

5.4.3 逻辑运算符

and(与), or(或),not(非)

举报

相关推荐

Mysql基本操作

MySQL 基本操作

MySQL基本操作

MySql基本操作

mysql -- 基本操作

cadence——基本操作3

MySQL基本操作5

0 条评论