Mysql基础篇之表的操作

建立表如下:

create table User(
id int primary key auto_increment,
name varchar(10),
sex boolean,
age int(3));
auto_increment是mysql的特色语句,该属性值自动增加,每个都不一样,比较适合作为主键(当然不是必须的)。

多字段主键的代码如下:

create table Student(
stu_id int,
course_id int,
age int,
primary key(stu_id,course_id));
设置外键代码:

create table Worker(
stu_id int,
Post varchar(33),
Department varchar(33),
constraint ctr foreign key(stu_id) references Student(stu_id));
对于这个情况外键是单字段,其实可以不用constraint设置一个别名 ctr的,对于多字段的外键约束可以用这样的方法在括号里面多加几个属性用逗号隔开,而用一个别名ctr表示,删除起来比较容易。而如果不用constraint设置 别名,系统也会自动初始化别名,通过show create table Worker;(后面可以加个  \G  使得结果好看一点)命令可以查看到系统生成的别名。

约束除了主键,外键,自动增加,还有not null,unique,default。位置跟主键是一样的。对于default使用方法这样:

number double default 0,

对于表结构查看

describe Worker;
desc Worker;
这两个是一样的。
对于表名和表属性的修改删除添加,都可以用alter命令搞定。
更改表名:

alter table Student rename pupil;
修改数据类型:

alter table Student modify course_id varchar(33);
修改字段名:

alter table Student change course_id course varchar(33);
新字段名类型可以不改,也可以改,但是不能没有,语法不允许。

增加字段:

alter table Student add phone int(12) after stu_id;
after可以不写,默认添加在最后一个字段的后面,也可以写first(只有一个first),加字段到开头。字段名可以添加约束,跟建表时的字段语法是一样的。

删除字段:

alter table Student drop phone;

如果字段是外键,需要在被删除属性名前加个 foreign key

修改字段位置:

alter table Student modify age int(11) first | after stu_id;
属性名每个都不能多也不能少。。。。。倒霉语法。不过仔细想想也是对的,要移动的字段带着类型可以知道移动范围,而在谁后面只需要找到位置就可以了(-_-反正得找个方法记下来)。
存储引擎也是可以用alter改的:

alter table Student engine=MyISAM;
删除表就很简单了

drop table Student;

添加索引

alter table Student add index(stu_id);

删除主键:

alter table Student drop primary key;
添加主键:

alter table Student add primary key (stu_id,age);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值