我感觉您需要阅读有关如何在表之间创建关系,尤其是外键的概念。
这是我对您描述的架构的再现:
# 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`)
);
我希望这会有所帮助。