MYSQL开发- (1)

use mydb2

--1:用户表,存储博主和评论者信息

create table users(

id int primary key auto_increment comment '用户ID,主键',

username varchar(50) not null unique comment '用户名,唯一',

email varchar(100) not null unique comment '邮箱,唯一',

password_hash varchar(225) not null comment '加密后的密码',

avatar_url varchar(255) default '' comment '头像图片链接',

created_at TIMESTAMP default CURRENT_TIMESTAMP comment '创建时间'

)comment '用户表'

--2:文章表,存储博客文章

create table posts(

id int primary key auto_increment comment '文章ID,主键',

user_id int not null comment '作者ID,关联users.id',

title varchar(200) not null comment '文章标题',

content TEXT not null comment '文章正文',

summary varchar(500) comment '文章摘要',

view_count int default 0 comment '阅读数',

status ENUM('draft','published') default 'draft' comment '状态:草稿,已发布',

created_at TIMESTAMP default current_timestamp comment '创建时间',

updated_at TIMESTAMP default current_timestamp on update current_timestamp comment '最后更新时间',

FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ---键约束:用户删除则文章级联删除

) comment '文章表'

--3:评论表:存储对文章的评论

create table comments(

id int primary key auto_increment comment '评论ID,主键',

post_id int not null comment '所属文章ID,关联posts.id',

user_id int not null comment '评论者ID,关联users.id',

content TEXT not null comment '评论内容',

parent_id int default null comment '父评论ID(用于回复功能),自关联',

created_at TIMESTAMP default current_TIMESTAMP COMMENT '创建时间',

foreign key(user_id) references posts(id) on delete caseade, -- 文章删除则评论级联删除

foreign key(user_id) references users(id) on delete caseade -- 用户删除则评论级联删除

)comment '评论表'

-- 1. 插入模拟数据

INSERT INTO users (username, email, password_hash) VALUES

('小明', 'xiaoming@example.com', 'hash_of_password_123'),

('技术博主', 'tech@example.com', 'hash_of_password_456');

INSERT INTO posts (user_id, title, content, status) VALUES

(1, '我的第一篇博客', '今天天气真好,我开始写博客了...', 'published'),

(2, 'MySQL入门指南', '关系型数据库是Web开发的基石...', 'published'),

(2, '未完成的草稿', '这是一个还在构思中的文章...', 'draft');

INSERT INTO comments (post_id, user_id, content) VALUES

(1, 2, '欢迎加入博客圈!'),

(2, 1, '写得非常清晰,对我帮助很大!'),

(2, 2, '谢谢支持,欢迎持续关注。');

---基础查询练习

--查询所有已经发布的文章(按发布时间倒序)

select * from posts where status = 'published' order by created_at desc

相关推荐
雨辰AI5 小时前
生产级实战:人大金仓 V9 标准化运维手册(日常巡检 + 监控告警 + 应急处置)
java·运维·数据库·后端
我是一颗柠檬5 小时前
【Java项目技术亮点】覆盖索引与索引下推优化
android·java·开发语言
云道轩5 小时前
比较IBM Transformation Advisor 和WebSphere Application Server Migration Toolkit
java·jakarta ee·open liberty·应用迁移
2601_962440845 小时前
计算机毕业设计之健身房管理系统的设计与实现
java·开发语言·课程设计·旅游·宠物
TeamDev5 小时前
JxBrowser 9.3.0 版本发布啦!
java·后端·c#·混合应用·jxbrowser·浏览器控件·异步媒体设备
深盾科技_Virbox5 小时前
深盾科技·Virbox产品体系全景解读:软件安全如何从加密锁走向全生命周期
java·大数据·算法·安全·软件需求
豆瓣鸡5 小时前
Knife4j 接口文档
java
格子软件5 小时前
2026年GEO优化系统源码的分布式状态机深度拆解
java·前端·vue.js·vue·geo
C++、Java和Python的菜鸟5 小时前
第1章 集合高级
java·jvm·python
ShiXZ2135 小时前
PDF-OCR文件识别篇(八):配置、运维与排错
java·运维·ocr·dubbo·springboot