我正在尝试为市场网站设置数据库表,我在设置这些表时遇到了一些困难。
我有大约18个类别,每个类别都有很多儿童类别。因此,我创建了一个名为category的表,列出了18个类别,列有以下列:id、category_name、position、visible。
我为每个类别做了一个表格,因为每个类别都有不同的属性。例如,real estate具有与automobiles不同的属性。最后,我得到了18张表:每种表一张。
images表,还是为所有类别创建一个images表?发布于 2016-01-23 13:41:56
我觉得您需要了解如何在表之间创建关系,特别是外键的概念。
下面是我对您描述的模式的表示:
# Our main table
CREATE TABLE `categories` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
# Regular foreign key
`image_id` int(11) unsigned NOT NULL,
# Polymorphic foregin key
`category_table` enum('automobiles','real_estate') NOT NULL,
`category_id` int(11) unsigned NOT NULL,
# Common category data
`name` text NOT NULL,
`position` smallint(5) NOT NULL,
`visible` enum('yes','no') NOT NULL,
PRIMARY KEY (`id`),
# Foreign key constraints
UNIQUE KEY `category_table` (`category_table`,`category_id`),
KEY `image_id` (`image_id`)
);
# A child table that stores automobile specific data
# - `categories` table refers to its records via `category_id` part of the foreign key, when `category_table` equals 'automobiles'
CREATE TABLE `categories_automobiles` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`make` varchar(255) NOT NULL,
`model` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);
# A child table that store automobile specific data
# - `categories` table refers to its records via `category_id` part of the foreign key, when `category_table` equals 'real_estate'
CREATE TABLE `categories_real_estate` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`squarespace` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`)
);
# A table that stores images
# - `categories` table refers to its records via `image_id` foreign key
# - other tables may refer to its record as well
CREATE TABLE `images` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
# Either store image data itself in this table
`image_data` blob NOT NULL,
# or store file path to the image
`image_path` text NOT NULL,
PRIMARY KEY (`id`)
);我希望这能帮到你。
https://stackoverflow.com/questions/34963623
复制相似问题