我有一種感覺,你需要閱讀如何創建表之間的關係,特別是外鍵的概念。
這裏是我的,你所描述的模式的再現:
# 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`)
);
我希望這有助於。
編輯正確,以便我們能夠理解 –
@PathikVejani在StackOverflow上,每個人都可以編輯問題以添加更多空格... –
對不起,我是StackOverflow的新手,會嘗試編輯它! – Samwise