表的基本操作

1.表的创建语法

CREATE TABLE table_name (
field1 datatype,
field2 datatype,CREATE TABLE table_name (
field1 datatype,
field2 datatype,
field3 datatype
) character set 字符集 collate 校验规则 engine 存储引擎;
注意:field 表示列名
datatype 表示列的类型
character set 字符集,如果没有指定字符集,则以所在数据库的字符集为准
collate 校验规则,如果没有指定校验规则,则以所在数据库的校验规则为准
例如:create table users (
id int,
name varchar(20) comment '用户名',
password char(32) comment '密码是32位的md5值',
birthday date comment '生日'
) character set utf8 engine MyISAM;
field3 datatype
) character set 字符集 collate 校验规则 engine 存储引擎;
注意:field 表示列名
datatype 表示列的类型
character set 字符集,如果没有指定字符集,则以所在数据库的字符集为准
collate 校验规则,如果没有指定校验规则,则以所在数据库的校验规则为准
例如:create table users (
id int,
name varchar(20) comment '用户名',
password char(32) comment '密码是32位的md5值',
birthday date comment '生日'
) character set utf8 engine MyISAM;

 2.查看表结构:

desc 表名;

 3.查看表:

show tables;

 4.查看表元素:

 select * from 表名;

 5.显示表的创建语句:

show create table 表名;

 6.字段的操作

.添加字段:alter table 表名 add age afer name;(表示把age插入到name后面)
.修改类型:alter table 表名 modify name varchar(60);(表示将name长度变为60)
.删除字段:alter table 表名 drop password;

 7.修改表名:

alter table 表名 rename to 新表名;

 8.修改字段名:

alter table 表名 change name xingming varchar(60);把name修改为xingming,新字段重新定义

9. 删除表:

drop table 表名;

 10.查询

查询某一项:select * from 表名 where hobby=‘登山’;
集合查询:例如:select * from 表名 where find_in_set(‘登山’,hobby);在hobby查找爱好登山的人
select find_in_set('a','a,b,c');在abc中查a的位置;

 11.表的约束:

空属性 not null、默认值default和列描述comment
例子:create table tt(
name varchar(20) not null comment ‘姓名’ ,
age int unsigned default 0 comme ‘年龄‘,
sex enum('男','女') default'男' comment ’性别’);

12. 表的约束键

主键(primary key)、自增长(auto_increment)、唯一键(unique)
单主键:id int unsigned primary key auto_incream,
复合主键:例如:create table tt(
name varchar(20) not null  unique comment ‘姓名’ ,
age int unsigned default 0 comme ‘年龄‘,
sex enum('男','女') default'男' comment ’性别’,
primary key(name,age));

13. 外键(需要创建两张表,主键表和从表)

先创建主键表:create table myclass(
id int primary key,
name varchar(20) not null );
再创建从表: create table stu(
id int primary key,
name varchar(30) not null ,
class_id int,
foreign key (class_id) references myclass(id));

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值