MySQL数据库基础(1)

tech2022-08-20  83

1.数据库操作

显示数据库

show databases;

创建数据库

create database 数据库名;

使用数据库

use 数据库名;

删除数据库

drop database if exists 数据库名;

2.常用数据类型

数值类型 数据类型大小说明BIT[(M)]M指定位数,默认为1二进制数,M范围从1到64,存储数值范围从0到2^M-1SMALLINT2字节INT4字节BIGINT8字节FLOAT(M,D)4字节单精度,M指定长度,D指定小数位数。会发生精度丢失。DOUBLE(M,D)8字节DECIMAL(M,D)M/D最大值+2双精度,M指定长度,D表示小数位数。精确数值NUMERIC(M,D)M/D最大值+2和DECIMAL一样 字符串类型 数据类型大小说明VARCHAR (SIZE)0-65535字节可变长度字符TEXT0-65535字节长文本数据MEDIUMTEXT0-16 777 215字节中等长度文本数据BLOB0-65535字节二进制形式的长文本数据 日期类型 数据类型大小说明DATETIME8字节范围从1000到9999年,不会进行时区的检索及转换。TIMESTAMP4字节范围从1970到2038年,自动检索当前时区并转换。

3.表操作

查看表结构

desc 表名;

示例:

创建表

示例:可以使用comment增加字段说明。

create table sc( id int, name varchar(20), chinese decimal(3,1), math decimal(3,1), english decimal(3,1) );

删除表

删除表: drop table 表名; 如果要删除的表存在,则删除表: drop table if exists 表名;

4.基本语句

新增数据

(1)单行数据+全列插入:

示例: insert into sc values (1,‘张三’,80,91,70); insert into sc values (2,‘admin’,80.5,97,91);

(2)多行数据+指定列插入:

示例: insert into sc(id,name) values (3,‘root’), (4,‘baby’);

查询数据

(1)全列查询:

示例: select * from sc;

(2)指定列查询:

示例: select name from from sc;

(3)使用distinct关键字去重:

去重之前对math进行查询:

去重之后: (4)排序:order by

asc 为升序,示例:

desc为降序,示例:

(5)条件查询(where) 基本查询:

示例:查询math大于90的学生及成绩 select name,math from sc where math>90;

and与or:

示例: select * from sc where math>90 or chinese>80 and english >70;

范围查询:between…and… 和 in

示例: select name,math from sc where math between 70 and 80; select name,math from sc where math in (78,90,91,92);

模糊查询:like

%匹配任意多个字符: select name from sc where name like ‘孙%’; 匹配严格的任意一个字符: select name from sc where name like ‘孙_’;

NULL的查询:

math不为空: select * from sc where math is not null; math为空: select * from sc where math is null;

(6)分页查询:limit 从0开始,筛选n条结果:

select * from sc limit n;

从s开始,筛选n条结果:

select * from sc limit s,n; select * from sc limit n offset s;

修改数据

示例:将name为‘admin’的同学的math改为60 update sc set math=60 where name=‘admin’;

删除数据

删除id为4的信息: delete from sc where id=4; 删除整表数据: delete from sc;

最新回复(0)