24.DDL语句使用

模板

create database if not exists music_Top character set utf8mb4 collate utf8mb4_unicode_ci;

use music_Top;

create table if not exists songInfo(
    id int primary key auto_increment comment '歌曲ID,自增',
    song_name varchar(20) not null comment '歌曲名字,不能为空',
    song_Info varchar(75)   comment '歌曲信息',
    song_url varchar(100)  comment '歌曲播放源地址'
) ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci comment '歌曲信息表';

create table if not exists author(
    id int primary key auto_increment comment '歌曲作者id',
    name varchar(10) not null comment '作者名字',
    Info varchar(75) comment '作者信息',
    email varchar(30) comment 'Email地址',
    address varchar(30) comment '居住地址',
    songInfo_id int not null comment '关联歌曲id,不能为空',
--添加外键约束
    constraint fk_author_songInfo_id foreign key (songInfo_id) references songInfo(id) on delete cascade
 )ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci comment '作者信息表';

create table if not exists picture(
    id int primary key auto_increment comment '歌曲图片id',
    picture_url varchar(100) comment '歌曲图片源',
    songInfo_id int not null comment '关联歌曲信息id,不能为空',
    constraint fk_picture_songInfo_id foreign key (songInfo_id) references songInfo(id) on delete cascade
)ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci comment '歌曲图片信息表';

1.添加外键
image

2.移除外键

ALTER TABLE 表名 DROP FOREIGN KEY 外键约束名;

3.级联(cascade)

行为 说明
NO ACTION 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新。(与 RESTRICT 一致)
RESTRICT 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新。(与 NO ACTION 一致)
CASCADE 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有,则也删除/更新外键在子表中的记录。
SET NULL 当在父表中删除对应记录时,首先检查该记录是否有对应外键,如果有则设置子表中该外键值为null(这就要求该外键允许取null)。
SET DEFAULT 父表有变更时,子表将外键列设置成一个默认的值 (Innodb不支持)

用法

ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY(外键字段)REFERENCES 主表名(主表字段名)ON UPDATE CASCADE ON DELETE CASCADE;

4.给表新增字段

ALTER TABLE music_top.songinfo ADD hot_score INT(4) comment '热度';
posted @ 2025-12-16 11:26  那就改变世界吧  阅读(30)  评论(0)    收藏  举报