Table(InnoDB):
CREATE TABLE `product_category` (
`product_id` int(11),
`category_id` int(11),
PRIMARY KEY (`product_id`,`category_id`),
UNIQUE KEY `category_id` (`category_id`,`product_id`)
)我需要在我的项目中运行以下SQL查询:
1. select `category_id` from `product_category` where `product_id`=?
2. select `product_id` from `product_category` where `category_id`=?我为SQL查询1创建PRIMARY KEY(product_id,category_id)。
并为SQL查询2创建UNIQUE(category_id,product_id)键。
我想知道是吗?
还有其他优化的可能吗?
非常感谢
发布于 2012-03-13 16:22:49
如果您使用的是INNODB引擎,则不需要第二个复合索引(在category_id,product_id上)。仅在category_id上有一个索引就足够了,因为所有辅助索引都保留主键的副本
发布于 2012-03-13 16:32:43
如果您已经为这些字段创建了主键(如果一组列是主键,那么该集合也是唯一的),则不应该为这些字段创建唯一约束。
您可以将字段单独设置为惟一字段,但前提是必须确保category_id具有单个product_id,而product_id具有单个category_id。从名称我推断,一个类别可能有更多的产品,一个产品可能是更多类别的一部分。如果是这种情况,那么根本不应该创建唯一的约束。
优化:如果您没有那么多的类别或产品,您应该将这些字段定义为更小的大小(可能是int(5))。
https://stackoverflow.com/questions/9687847
复制相似问题