sql语句exercise

ALTER 是 SQL(Structured Query Language,结构化查询语言)中的一个关键字,用于修改数据库表的结构。使用 ALTER 语句可以执行多种操作,比如添加、删除或修改列,修改列的数据类型,添加或删除约束等。

修改表名的语句:

alter tab

1.

添加列

ALTER TABLE table_name
ADD column_name column_type;

.

删除列

ALTER TABLE table_name
DROP COLUMN column_name;

修改列的数据类型

ALTER TABLE table_name
MODIFY column_name new_column_type;


或者在某些数据库系统中使用:

ALTER TABLE table_name
ALTER COLUMN column_name TYPE new_column_type;

修改列名

ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;

添加主键约束

ALTER TABLE table_name
DROP PRIMARY KEY;

添加外键约束

ALTER TABLE table_name
ADD CONSTRAINT fk_name FOREIGN KEY (column_name) REFERENCES other_table(other_column);

删除外键约束

ALTER TABLE table_name
DROP FOREIGN KEY fk_name;

查询唯一约束名称:

删除唯一约束:

alter tabler 表名 drop index 字段;

创建班级表:

create table 表名 (
cid int PRIMARY key,
cname VARCHAR(50) UNIQUE
);

创建学生表

create table if not exists student(
id int PRIMARY KEY,
name VARCHAR(10),
gender enum('男',‘女’),
birthday date,
age int,
classId int,
begin_year year 

);

添加外键:

一:当表已存在,通过修改表的方式添加外键

Alter table 表名 add foreign key(classid) references 表名(字段名)

二:创建表的时候添加外键约束

第一步,必须先创建主表:
create table t_class1(
cid int primary key ,
cname carcher(50) unique
);

第二步:创建从表:

create table if not exists student01(
id int primary key,
name varcher(10),
gender enum('男','女'),
birthday date,
age int ,
class_id int ,
begin year,
foreign key (calss_id) references  t_class1(cid)
);

查看外键约束名

select *from information_schema.key_column_usage where table_schema=’school_db1′ and table_name=’student1′

删除外键约束:

alter table student1 drop foreign key student1_ibfk_1;

#非空约束

添加非空约束

方法一:

create table t_stu1(

id int primary key,

name varcher(50) not null

)

desc t_stu;

方法二:

ALTER table t_stu MODIFY id int not null;

删除非空约束

ALTER ATBLE t_stu modify id int;

#####自增约束

添加自增约束

方法一:

create table t_stu2(

id int primary key AUTO_INCREMENT,

name varcher(50) not null

);

方法二:

alter table t_stu2 modify id int primary key AUTO_INCREMENT;

DESC t_stu;

删除自动递增:

alter table t_stu modify id int ;

###

check 约束:

添加check约束:

WAY 一:

create table if not exists student2(

id int primary key ,

name varcher(10) check (LENGTH)>=2,

gender ENUM(‘男’,’女’),

birthday date ,

age int check(age >=18 and age<=25),

classId int,

begin_year year,

froeign key (classid) references t_class1(cid)

);

查询check约束:

select *from information_schema.check_constraints;

删除checkl约束

Alter table student2 drop check student2_chk_2;

博客内容均系原创,未经允许严禁转载!
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇