-- 创建用户表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 创建文章表
CREATE TABLE `post` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id_idx` (`user_id`),
CONSTRAINT `post_user_id_fk` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 创建评论表
CREATE TABLE `comment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`post_id` int(11) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`),
KEY `post_id_idx` (`post_id`),
CONSTRAINT `comment_post_id_fk` FOREIGN KEY (`post_id`) REFERENCES `post` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 插入用户数据
INSERT INTO `user` (`name`) VALUES ('Alice'), ('Bob');
-- 插入文章数据
INSERT INTO `post` (`user_id`, `title`, `content`) VALUES
(1, 'Alice Post', 'Alice post content'),
(2, 'Bob Post', 'Bob post content');
-- 插入评论数据
INSERT INTO `comment` (`post_id`, `content`) VALUES
(1, 'Alice Comment'),
(2, 'Bob Comment');
-- 查询文章及其关联的评论
SELECT p.title, c.content
FROM post p
JOIN comment c ON p.id = c.post_id
WHERE p.user_id = 1;
这个例子展示了如何创建用户、文章和评论表,以及如何通过外键约束来建立它们之间的关联。当用户或文章被删除时,相关的评论也会通过级联删除自动被删除。最后,我们通过一个查询来演示如何通过JOIN查询来获取文章及其关联的评论。