根据juergen d 提供的应用程序、读取/写入次数等,您可以使用查找表来存储配对信息。
如果您的类别集有限(64 或更少),那么您可以选择避免查找表的开销并使用SET 字段。它是非规范化的,但意味着您可以从单行中检索类别以及产品。
然后您还可以进行按位比较以查找属于某个类别/类别集的产品,例如
mysql> show create table products\G
*************************** 1. row ***************************
Table: products
Create Table: CREATE TABLE `products` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`product_categories` set('a','b','c') DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `product_categories` (`product_categories`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
mysql> insert into products set name = 'product a', product_categories = 'a';
Query OK, 1 row affected (0.00 sec)
mysql> insert into products set name = 'product b', product_categories = 'b';
Query OK, 1 row affected (0.01 sec)
mysql> insert into products set name = 'product ab', product_categories = 'a,b';
Query OK, 1 row affected (0.01 sec)
mysql> select id, name from products where product_categories & 1;
+----+------------+
| id | name |
+----+------------+
| 1 | product a |
| 3 | product ab |
+----+------------+
2 rows in set (0.00 sec)
mysql> select id, name from products where product_categories & 2;
+----+------------+
| id | name |
+----+------------+
| 2 | product b |
| 3 | product ab |
+----+------------+
2 rows in set (0.00 sec)
mysql> select id, name from products where product_categories = 'a';
+----+-----------+
| id | name |
+----+-----------+
| 1 | product a |
+----+-----------+
1 row in set (0.00 sec)