mysql 表操作

本文详细介绍了MySQL中创建表、编辑表(包括添加字段、修改字段、更改字段名和表重命名)的操作,以及各种表约束,如无符号类型、自动填充、自增、非空和默认值。通过示例代码展示了如何使用SQL语句进行具体操作,并强调了索引在提高数据检索效率中的作用。
摘要由CSDN通过智能技术生成

提示:


一、创建表

create table [if not exists] 表名(
	字段名  字段类型  [字段约束] [comment '注释'] [索引类型],
	[primary key 字段名 ,]
	[index 索引名 (字段名 [,字段名]),]
	[unique 索引名 (字段名 [,字段名]),]
);

示例:

create table user(
	id int(11)   unsigned auto_increment  not null comment '主键' ,
	username char(20) not null,
	usernickname varchar(200) not null unique,
	birth_date date not null,
	primary key (id),
	index username_index(username),
	index username_birth_date_index(username,birth_date),
	unique username_birth_date_unique(usernickname,birth_date)
)

提示: primary key(主键索引) 和unique(唯一索引)是可以直接写到字段名那行,常规索引是需要在声明完所有字段后,使用index 进行声明
索引帮助mysql高效获取数据排好序的数据结构。

二、编辑表(alter)

修改表语法:alter table 表名 action;

1.添加字段

alter table 表名 add 字段名 <建表语句> [FIRST|AFTER 列名]

代码如下(示例):

alter table user add telno char(11) not null after usernickname;

2.修改字段(除字段名)

alter table 表名 modify 字段名 <建表语句>

代码如下(示例):

alter table user change telno varchar(11) not null after birth_date;

3.修改字段(并修改字段名)

alter table 表名 change 旧字段名 新字段名 <建表语句>

代码如下(示例):

alter table user change telno mobile varchar(11) not null after borth_date;

4.给表重命名

alter table 表名 rename as 新表名

代码如下(示例):

alter table user rename as user_employee;

三、表约束

1. unsigned 无符号类型

(用于设置数值类型,不允许出现负数)

2. zerofill 自动用0补齐

(设置数值类型,在数值之前自动用0补齐不足的位数)

3. auto_increment自增1

4.null 和 not null

5.default设置默认值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值