A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 Jessie001 于 2018-11-1 10:39 编辑

-- 对主键进行操作
create table test(
id int ,
name VARCHAR(20)
);

desc test;

--  添加主键
ALTER TABLE test ADD PRIMARY KEY ( id);


-- 删除主键

alter table test drop PRIMARY key;

-- 删除主键报错的情况  [Err] 1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key

create table test2(
id int PRIMARY key auto_increment,
name VARCHAR(20)
);

alter table test2 drop PRIMARY key;


-- 需要先删除自增长再删除主键
-- 删除自增长

Alter table test2 change id id int;
desc test2;
-- 然后再删除主键
alter table test2 drop PRIMARY key;


唯一约束


-- 创建表之后才想起来要给某个字段添加唯一约束???
create table test3(
id int PRIMARY key,
name VARCHAR(20)
);

-- 添加唯一约束

alter table test3 add UNIQUE (name);
desc test3;

-- 删除唯一约束


ALTER TABLE test3 DROP INDEX name; -- 唯一约束也是索引

-- 删除外键约束
CREATE table category (
c_id int primary key auto_increment,
c_name varchar(10));
  

CREATE TABLE product (
p_id int PRIMARY KEY auto_increment,
p_name varchar(10),
p_price INT,
category_id INT,
FOREIGN KEY (category_id) REFERENCES category(c_id));

-- 删除外键,报错???
alter table product drop foreign key category_id;

-- 观察 :
执行语句:
insert into product(p_name,p_price,category_id) VALUES('aa',100,9);
运行结果:
--- Cannot add or update a child row: a foreign key constraint fails (`temp2`.`product`, CONSTRAINT `product_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `category` (`c_id`))

-- 删除默认的外键约束名字
执行语句:alter table product drop foreign key product_ibfk_1;


-- 正解 :可在创建表的时候给外键约束取个别名方便后期使用

CREATE TABLE product (
p_id int PRIMARY KEY auto_increment,
p_name varchar(10),
p_price INT,
category_id INT,
CONSTRAINT cate_id FOREIGN KEY (category_id) REFERENCES category(c_id));


alter table product drop foreign key cate_id;

3 个回复

正序浏览
回复 使用道具 举报
回复 使用道具 举报
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马