数据库的基本操作

数据库操作表

增:

语法:create table 表名(

字段名 列类型 [可选参数],

字段名 列类型 [可选参数],

......

字段名 列类型 [可选参数] #最后一行不需要逗号

)charset=utf8;

列约束也有好几种:

auto_increment:自增

primary_key:主键索引

not null :该字段不能为空

default:为该字段设置默认值

create table t1(
	id int,
    name char(5)
)charset=utf8;

增加数据:

​ 语法:

​ insert into 表名(列1,列2..)values(值1,值2...);

​ 例子:

	insert into t1 (id,name)value(1,echo);

	insert into t1 (id,name)value(2,echo2);

查询数据:

​ 语法:

​ select 列1,列2..from 表名;

​ 例子:

​ select * from t1;

例子2:

create table t3(
    id  int unsigned auto_increment primary key,
    name char(10) not null default 'xxx',
    age int not null default 0
)charset=utf8;

这是最推荐使用的模板

mysql>insert into t3 (age)value(10);#因为id会自动叠加,因此为1,name有默认值为xxx  , age被设置为了10 最后的结果是 1,xxx,10

列类型光是数字就有好多种:

整型:

​ tinyint

​ smallint

​ int

​ mediumint

​ bigint

​ 整数类型

​ 取值范围

​ unsigned 加上之后代表不能取负值,只适用于整型

​ 应用场景:

​ 根据业务的场景来选取合适的类型

浮点型:

​ float:不一定精确

​ double:和float差不多

​ decimal:非常精确的数字(5000.23) decimal(6,2)#6代表一共有六位,2代表小数点之后还有两位.

字符串:

​ char(长度):定长

​ varchar(长度):变长

​ char(4),不管后面输入的有多长,到时候的字符串长度也只有四

​ varchar(4),只要输入的值的长度在前面输入的数字范围之内,都可以弹性长度为 字符长度+1,多出来的一个字符用来记录长度会改变

时间日期类型:

​ year(一般不用)

​ date(一般不用)

​ time(一般不用)

​ datetime:YYYY-MM-DD HH:MM:SS

​ timestamp(一般不用)

​ id int auto_increment primary key,

​ name char (10)

)charset=utf8;

​ insert into t2 (name) values ('')

改:

​ 修改表名

​ alter table 旧表名 rename 新表名;

​ alter table t8 rename t88;

​ 增加字段

​ alter table 表名

​ add 字段名 列类型 [可选的参数],

​ add 字段名 列类型 [可选的参数];

​ alter table t88 add name varchar(32) not null default '';

​ 删除字段

​ ALTER TABLE 表名 DROP 字段名;

​ 修改字段

​ ALTER TABLE 表名 MODIFY 字段名 数据类型 [完整性约束条件…];

​ Alter table 表名 change 旧字段名 新字段名 新数据类型[完整性约束条件...];

删:

语法

​ drop table 表名;

例子

​ drop table t9;

查:

​ show tables;

复制表的结构:

show create table t88;

然后复制显示的内容

或者

create table t89 like t88;

操作表数据行:

增:

​ 增加数据:

​ 语法:

​ insert into 表名(列1,列2)value (值1,值2);

​ insert into t66 (name)select name from t6;

删:

​ delete from 表名 where 条件;

​ delete from 表名; 删除表中所有的数据,逐条删除的

​ truncate 表名;直接全部删除的

​ 如: truncate t5;

​ 区别:

​ 1. delete之后,插入数据从上一次主键自增加1开始, truncate则是从1开始 2. delete删除, 是一行一行的删除, truncate:全选删除 truncate删除的 速度是高于delete的.

改:

​ update 表名 set 列名1=新值1 ,列名2=新值2 where 条件;

​ update t66 set name ='xxxx' where id=30;

查:

​ select 列1, 列2 from 表名;

​ select * from t66 where id between 30 and 40 ;#包括30和40的

​ 去重:select distinct name from t66;

​ select name,age*10 from t3;#尽量不要用

​ select * from t66 where id in (23,34,11);#也尽量不要用

模糊查询(%):

​ select * from t66 where name like 'x%'; x开头的所有元素

原文地址:https://www.cnblogs.com/jimGraymane/p/11761055.html