I assume that a product can belong to many categories, and a category (obviously) has many products in it. This relationship is called the many-to-many relationship.
In this case, you will have three tables: categories , products and categories_products . The first two tables are self-explanatory. The third table stores the relationship between the two with two foreign keys. The tables look like this:
CREATE TABLE `categories` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `parent_id` int(10) unsigned DEFAULT NULL, `name` varchar(45) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`), KEY `parent_id` (`parent_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `categories_products` ( `category_id` int(10) unsigned NOT NULL, `product_id` int(10) unsigned NOT NULL, KEY `category_id` (`category_id`), KEY `product_id` (`product_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `products` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `categories_products` ADD CONSTRAINT `categories_products_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `categories_products_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
Obviously, these are schema tables on their simplest. You will need to add your additional columns to the categories and products table-Ive tables, including only the columns corresponding to the relationship.
EDIT: I also added a parent_id column to the categories table for nesting categories. It's usually a bad idea to create a separate sub_categories table - what happens if you want to make a subcategory of a top-level category? Or vice versa? You were mistaken for the lack of a better phrase.
Martin bean
source share