如何设置数据库表,数据库设计

时间:2016-01-23 12:44:05

标签: mysql database-design database-schema

我正在尝试为市场网站设置数据库表,我在设置表时遇到了一些困难。

我有大约18个类别,每个类别都有很多子类别。所以我创建了一个名为category的表格,列出了18个类别,其中包含以下列:idcategory_namepositionvisible

我为每个类别制作了一个表格,因为每个类别都有不同的属性。例如,real estate具有与automobiles不同的属性。所以我最终得到了18个表:每个类别一个表。

  1. 第一个问题:我是否正确为每个类别创建表格?
  2. 第二个问题:每个类别表格中的每一行代表一个项目的广告。我对如何为图像设置表感到困惑。每个广告都有一组图片。

    所以问题是:我应该为每个父类别创建一个images表,还是可以为所有类别创建一个images表?

1 个答案:

答案 0 :(得分:0)

我觉得您需要了解如何在表之间创建关系,特别是外键的概念。

以下是我所描述的架构的再现:

# 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`)
);

我希望这会有所帮助。

相关问题