如何设置数据库表,数据库设计
我想为市场网站设置数据库表,我在设置表时遇到了一些困难。如何设置数据库表,数据库设计
我有大约18个类别,每个类别都有很多子类别。所以我制作了一张名为category
的表格,列出了以下列的18个类别:id
,category_name
,position
,visible
。
而且我为每个类别制作了一个表格,因为每个类别都有不同的属性。例如,real estate
与automobiles
具有不同的属性。所以我结束了18个表格:每个类别一个表格。
- 第一个问题:我是否正确地为每个类别创建表?
-
第二个问题:每个类别表中的每行代表一个项目的广告。我对如何设置图像表格感到困惑。每个广告都有一组图片。
所以问题是:我应该为每个父类别创建一个
images
表,或者它可以是所有类别的一个images
表?
我有一种感觉,你需要阅读如何创建表之间的关系,特别是外键的概念。
这里是我的,你所描述的模式的再现:
# 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`)
);
我希望这有助于。
非常感谢@chromice!我只是不明白你为什么把外键放在_parent table_中,我认为父表的表_primary key_必须是子表中的外键,并且我认为我们总是必须在子表中设置**约束**。 – Samwise
你可以把'category_id'放在'images'表格中,但是你不能在'tags'表中使用'images'表格,因为'images'表格中的每个记录都指向唯一的记录在“类别”表中;并且您将无法将多个'category'记录指向'images'表中的相同记录。至于多态关系,没有其他方法可以定义一对一的关系。如果子表具有指向主表的'category_id',则可以创建添加UNIQUE约束,即'categories'中的每个记录在* any *子表中只有一条记录。 – chromice
编辑正确,以便我们能够理解 –
@PathikVejani在*上,每个人都可以编辑问题以添加更多空格... –
对不起,我是*的新手,会尝试编辑它! – Samwise