随笔 - 56  文章 - 3 评论 - 0 阅读 - 2210
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5


-- 先创建表后关联外键
-- ALTER TABLE <数据表名> ADD CONSTRAINT <外键名>
-- FOREIGN KEY(<列名>) REFERENCES <主表名> (<列名>);

alter table info add constraint fk_info_depart foreign key info(depart_id) references depart(id);

 

-- 关联外键 创建表时关联外键

create table info(
id int not null auto_increment primary key,
name varchar(16) not null,
email varchar(32) not null,
age int,
depart_id int not null,
constraint fk_info_depart foreign key (depart_id) references depart(id)
)default charset=utf8;

 

--簡單版

create table user(
id int(11) not null auto_increment PRIMARY KEY,
username VARCHAR(80) not NULL,
password VARCHAR(120) not NULL
)

CREATE table article(
id int(11) not null auto_increment PRIMARY KEY,
title VARCHAR(200) not null,
content text not null,
u_id int(11) not null,
foreign key (u_id) references user(id)
)

 

 

--多对多 创建中间表 中间表关联对于的外键

CREATE TABLE `stu` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) NOT NULL,
`sno` VARCHAR(10) NOT NULL,
PRIMARY KEY (`id`)
)DEFAULT CHARSET=utf8;

 

CREATE TABLE `course` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) NOT NULL,
PRIMARY KEY (`id`)
)DEFAULT CHARSET=utf8;


CREATE TABLE `stu_course`(
`s_id` int(11) NOT NULL,
`c_id` int(11) NOT NULL,
CONSTRAINT fk_s_id FOREIGN key (s_id) references stu(id),
CONSTRAINT fk_c_id FOREIGN key (c_id) references course(id)
)

 

 

 

CREATE TABLE `categorys` (
`id` int(10) NOT NULL COMMENT '主键id',
`category_id` int(10) NOT NULL unique,
`category_page` int(10) NOT NULL COMMENT '目录页数',
`category_title` varchar(255) DEFAULT NULL COMMENT '标题',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `category_id` (`category_id`),
UNIQUE KEY `category_id_2` (`category_id`),
UNIQUE KEY `category_id_3` (`category_id`)
)


#设计外键表的时候 需要主表的主键当外键,或者非主键 但是该字段一定是要not null unique 并且字符类型一致 字符位数也要一致 同样是要是int(10)
CREATE TABLE `videos` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`category_id` int(10) not NULL,
`m3u8` text,
`v_cover` text,
`v_length` varchar(20) DEFAULT NULL,
`v_title` varchar(100) DEFAULT NULL,
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`),
KEY `fk_category_id` (`category_id`),
CONSTRAINT `fk_category_id` FOREIGN KEY (`category_id`) REFERENCES `categorys` (`category_id`)
)

ALTER TABLE categorys MODIFY category_id int(10) NOT NULL UNIQUE;

posted on   我爱你的  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示