当前位置: 代码网 > it编程>数据库>Mysql > MySQL实际项目中常用的 DDL 模板

MySQL实际项目中常用的 DDL 模板

2025年12月11日 Mysql 我要评论
✅ 一、建表模板(带审计字段 + 索引)create table `hot_campaign` ( `id` bigint not null auto_increment comment '主键

✅ 一、建表模板(带审计字段 + 索引)

create table `hot_campaign` (
    `id` bigint not null auto_increment comment '主键',
    `campaign_name` varchar(64) not null comment '活动名称',
    `site` varchar(32) not null comment '站点',
    `status` tinyint not null default 1 comment '状态:1启用 0停用',
    `created_at` datetime not null default current_timestamp comment '创建时间',
    `created_by` varchar(16) default null comment '创建人工号',
    `updated_at` datetime not null default current_timestamp on update current_timestamp comment '更新时间',
    `updated_by` varchar(16) default null comment '更新人工号',
    primary key (`id`),
    key `idx_site` (`site`),
    key `idx_status` (`status`)
) engine=innodb default charset=utf8mb4 comment='营销活动表';

✅ 二、修改表结构(add / drop / change / modify)

1)新增字段

alter table `hot_campaign`
add column `last_updated_staff` varchar(16) default null comment '最后更新人工号';

2)删除字段

alter table `hot_campaign`
drop column `last_updated_staff`;

3)修改字段类型(modify)

仅修改类型,不改字段名

alter table `hot_campaign`
modify column `campaign_name` varchar(128) not null comment '活动名称';

4)修改字段名 + 字段类型(change)

alter table `hot_campaign`
change column `status` `campaign_status` tinyint not null default 1 comment '活动状态';

5)修改字段默认值

alter table `hot_campaign`
alter column `status` set default 1;

✅ 三、索引相关(index / unique / drop)

1)新增普通索引

alter table `hot_campaign`
add index `idx_name` (`campaign_name`);

2)新增联合索引

alter table `hot_campaign`
add index `idx_site_status` (`site`, `status`);

3)新增唯一索引

alter table `hot_campaign`
add unique index `uk_site_name` (`site`, `campaign_name`);

4)删除索引

alter table `hot_campaign`
drop index `idx_site_status`;

✅ 四、外键(foreign key)

1)新增外键约束

alter table `coupon`
add constraint `fk_coupon_campaign`
    foreign key (`campaign_id`)
    references `hot_campaign` (`id`)
    on delete cascade
    on update cascade;

2)删除外键

alter table `coupon`
drop foreign key `fk_coupon_campaign`;

✅ 五、表结构变更

1)重命名表

rename table `hot_campaign` to `hot_campaign_v2`;

2)设置表的字符集

alter table `hot_campaign`
convert to character set utf8mb4 collate utf8mb4_unicode_ci;

✅ 六、删除表(drop)

drop table if exists `hot_campaign`;

到此这篇关于mysql实际项目中常用的 ddl 模板的文章就介绍到这了,更多相关mysql ddl模块内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com