首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何建立数据库表,数据库设计

如何建立数据库表,数据库设计
EN

Stack Overflow用户
提问于 2016-01-23 12:44:05
回答 1查看 224关注 0票数 0

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

我有大约18个类别,每个类别都有很多儿童类别。因此,我创建了一个名为category的表,列出了18个类别,列有以下列:idcategory_namepositionvisible

我为每个类别做了一个表格,因为每个类别都有不同的属性。例如,real estate具有与automobiles不同的属性。最后,我得到了18张表:每种表一张。

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

回答 1

Stack Overflow用户

发布于 2016-01-23 13:41:56

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

下面是我对您描述的模式的表示:

代码语言:javascript
复制
# 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`)
);

我希望这能帮到你。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34963623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档