I have two tables:
CATEGORY
category_id int(10) UNSIGNED AUTO_INCREMENT
category_title varchar(255)
PRODUCT
product_id int(10) UNSIGNED AUTO_INCREMENT
product_category int(10) UNSIGNED
product_title varchar(255)
Column product_category
is a foreign key related to category_id
. Here is some data:
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
How I can fetch all categories with the count of products?
category_id category_title products_count
----------- -------------- --------------
3 Cellphone 3
4 Motherboard 9
5 Monitor 7
I used this query:
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
But it takes too long: ( 254 total, Query took 4.4019 sec). How can I make this query better?
DESC
Adding DESC
before the query, give me this result:
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
SHOW CREATE TABLE
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;