2016-01-23 94 views
0

我想爲市場網站設置數據庫表,我在設置表時遇到了一些困難。如何設置數據庫表,數據庫設計

我有大約18個類別,每個類別都有很多子類別。所以我製作了一張名爲category的表格,列出了以下列的18個類別:id,category_name,position,visible

而且我爲每個類別製作了一個表格,因爲每個類別都有不同的屬性。例如,real estateautomobiles具有不同的屬性。所以我結束了18個表格:每個類別一個表格。

  1. 第一個問題:我是否正確地爲每個類別創建表?
  2. 第二個問題:每個類別表中的每行代表一個項目的廣告。我對如何設置圖像表格感到困惑。每個廣告都有一組圖片。

    所以問題是:我應該爲每個父類別創建一個images表,或者它可以是所有類別的一個images表?

+1

編輯正確,以便我們能夠理解 –

+0

@PathikVejani在StackOverflow上,每個人都可以編輯問題以添加更多空格... –

+0

對不起,我是StackOverflow的新手,會嘗試編輯它! – Samwise

回答

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

我希望這有助於。

+0

非常感謝@chromice!我只是不明白你爲什麼把外鍵放在_parent table_中,我認爲父表的表_primary key_必須是子表中的外鍵,並且我認爲我們總是必須在子表中設置**約束**。 – Samwise

+0

你可以把'category_id'放在'images'表格中,但是你不能在'tags'表中使用'images'表格,因爲'images'表格中的每個記錄都指向唯一的記錄在「類別」表中;並且您將無法將多個'category'記錄指向'images'表中的相同記錄。至於多態關係,沒有其他方法可以定義一對一的關係。如果子表具有指向主表的'category_id',則可以創建添加UNIQUE約束,即'categories'中的每個記錄在* any *子表中只有一條記錄。 – chromice