我正在创建一个简单的图片上传系统,该系统使用四个表user
,likes
,images
和comments
,用户可以在其中上传,例如和留言。我在mysql workbench
创建了我的表格,我的一张表格(计算了评论和图片的喜欢数量)与one-to-many
和{{images
的关系comments
1}}。我的问题是如何正确处理这个问题?或者我应该删除likes
表并将like_count
列放在images
和comments
表中?如何解决likes
,images
和comments
问题之间的这种关系?
用户表
CREATE TABLE IF NOT EXISTS `my_db`.`users` (
`user_id` INT NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR(255) NOT NULL,
`user_email` VARCHAR(60) NOT NULL,
`user_passwd` VARCHAR(255) NOT NULL,
`activated` VARCHAR(255) NOT NULL,
`user_registered` DATETIME NOT NULL,
`reset` VARCHAR(255) NULL DEFAULT NULL,
`users_pic` VARCHAR(255) NULL,
PRIMARY KEY (`user_id`),
UNIQUE INDEX `user_name_UNIQUE` (`user_name` ASC),
UNIQUE INDEX `user_email_UNIQUE` (`user_email` ASC))
ENGINE = InnoDB;
图片表。
CREATE TABLE IF NOT EXISTS `my_db`.`images` (
`image_id` INT NOT NULL AUTO_INCREMENT,
`users_user_id` INT NOT NULL,
`image_created` DATETIME NOT NULL,
PRIMARY KEY (`image_id`, `users_user_id`),
INDEX `fk_images_users_idx` (`users_user_id` ASC),
CONSTRAINT `fk_images_users`
FOREIGN KEY (`users_user_id`)
REFERENCES `my_db`.`users` (`user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
评论表
CREATE TABLE IF NOT EXISTS `my_db`.`comments` (
`comment_id` INT NOT NULL AUTO_INCREMENT,
`images_image_id` INT NOT NULL,
`images_users_user_id` INT NOT NULL,
`comment` VARCHAR(500) NULL,
`comment_created` DATETIME NOT NULL,
PRIMARY KEY (`comment_id`, `images_image_id`, `images_users_user_id`),
INDEX `fk_comments_images1_idx` (`images_image_id` ASC, `images_users_user_id` ASC),
CONSTRAINT `fk_comments_images1`
FOREIGN KEY (`images_image_id` , `images_users_user_id`)
REFERENCES `my_db`.`images` (`image_id` , `users_user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
喜欢桌子
CREATE TABLE IF NOT EXISTS `my_db`.`likes` (
`like_id` INT NOT NULL AUTO_INCREMENT,
`like_count` INT NOT NULL DEFAULT 0,
`like_dislike` INT NOT NULL DEFAULT 0,
`images_image_id` INT NOT NULL,
`images_users_user_id` INT NOT NULL,
`comments_comment_id` INT NOT NULL,
`comments_images_image_id` INT NOT NULL,
`comments_images_users_user_id` INT NOT NULL,
PRIMARY KEY (`like_id`, `images_image_id`, `images_users_user_id`, `comments_comment_id`, `comments_images_image_id`, `comments_images_users_user_id`),
INDEX `fk_likes_images1_idx` (`images_image_id` ASC, `images_users_user_id` ASC),
INDEX `fk_likes_comments1_idx` (`comments_comment_id` ASC, `comments_images_image_id` ASC, `comments_images_users_user_id` ASC),
CONSTRAINT `fk_likes_images1`
FOREIGN KEY (`images_image_id` , `images_users_user_id`)
REFERENCES `my_db`.`images` (`image_id` , `users_user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_likes_comments1`
FOREIGN KEY (`comments_comment_id` , `comments_images_image_id` , `comments_images_users_user_id`)
REFERENCES `my_db`.`comments` (`comment_id` , `images_image_id` , `images_users_user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;