我有两个表:
类别
category_id int(10) UNSIGNED AUTO_INCREMENT
category_title varchar(255)
产品
product_id int(10) UNSIGNED AUTO_INCREMENT
product_category int(10) UNSIGNED
product_title varchar(255)
列 product_category
是与 category_id
相关的外键。这是一些数据:
category_id category_title
----------- --------------
3 Cellphone
4 Motherboard
5 Monitor
product_id product_category product_title
---------- ---------------- -------------
3 3 Samsung Galaxy SIII
4 3 Apple iPhone 5
5 3 HTC One X
如何使用产品数量获取所有类别?
category_id category_title products_count
----------- -------------- --------------
3 Cellphone 3
4 Motherboard 9
5 Monitor 7
我使用了这个查询:
SELECT
`category_id` AS `id`,
`category_title` AS `title`,
COUNT( `product_id` ) AS `count`
FROM `ws_shop_category`
LEFT OUTER JOIN `ws_shop_product`
ON `product_category` = `category_id`
GROUP BY `category_id`
ORDER BY `title` ASC
但耗时太长:(共 254 次,查询耗时 4.4019 秒)。 我怎样才能使这个查询更好?
描述
在查询之前添加DESC
,给我这个结果:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE ws_shop_category ALL NULL NULL NULL NULL 255 Using temporary; Using filesort
1 SIMPLE ws_shop_product ALL NULL NULL NULL NULL 14320
显示创建表
CREATE TABLE `ws_shop_product` (
`product_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`product_category` int(10) unsigned DEFAULT NULL,
`product_title` varchar(255) COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`product_id`)
) ENGINE=MyISAM AUTO_INCREMENT=14499 DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE `ws_shop_category` (
`category_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`category_title` varchar(255) COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=MyISAM AUTO_INCREMENT=260 DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
最佳答案
您的表没有定义任何索引。不过,通过使用以下状态添加索引很容易补救:
ALTER TABLE `product` ADD INDEX `product_category` (`product_category`);
ALTER TABLE `category` ADD PRIMARY KEY(category_id);
现在,如果您再次运行查询,DESC
应该会告诉您查询使用了键并且应该会更快。
关于mysql - 如何计算与另一个表相关的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16997197/