我正在开始新项目,但不明白从哪里开始。我需要具有类别和 4 级子类别的数据库设计,但产品可以有多个类别。所以我很困惑我的数据库应该如何。请帮助我。非常感谢您提前给我时间。
user1625576
问问题
1923 次
1 回答
4
product: holds the products with id
category: hold the category with id and name AND the parent category of the category
product_category: holds the cross-relation between one or many products and one or many categories...
If you use InnoDB on mysql or a good DBMS you should define the foreign-key constraints:
CREATE TABLE IF NOT EXISTS `mydb`.`category` (
`id` INT NOT NULL ,
`name` VARCHAR(45) NULL ,
`parent_id` INT NULL ,
PRIMARY KEY (`id`) ,
INDEX `parentCategory_idx` (`parent_id` ASC) ,
CONSTRAINT `parentCategory`
FOREIGN KEY (`parent_id` )
REFERENCES `mydb`.`category` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `mydb`.`product` (
`id` INT NOT NULL ,
`name` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `mydb`.`product_category` (
`product_id` INT NOT NULL ,
`category_id` INT NOT NULL ,
PRIMARY KEY (`product_id`, `category_id`) ,
INDEX `product_idx` (`product_id` ASC) ,
INDEX `category_idx` (`category_id` ASC) ,
CONSTRAINT `product`
FOREIGN KEY (`product_id` )
REFERENCES `mydb`.`product` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `category`
FOREIGN KEY (`category_id` )
REFERENCES `mydb`.`category` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
于 2012-08-26T08:17:14.553 回答