我的网站 - 在线商店。 我需要显示类别表中的数据。 和此类别中的项目数。
表格中的行数 ITEMS约为6700 。
表 CATEGORY 123
中的行数我使用此查询:
SELECT c.* , COUNT( i.id ) count FROM category c LEFT JOIN items i ON
i.catid = c.catid GROUP BY c.id
此查询执行超过4秒。
EXPLAIN的结果: http://i.gyazo.com/c71c43af2719010cb5c4a2ad1d8cefd8.png
表类别:
CREATE TABLE IF NOT EXISTS `category ` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`catid` varchar(16) NOT NULL,
`url` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);
表项目:
CREATE TABLE IF NOT EXISTS ` items ` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`catid` int(11) NOT NULL,
`link` varchar(255) NOTNULL,
`title` varchar(255) NOT NULL,
`images` text NOT NULL,
`price` double NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
);
我该如何优化它?请帮忙
答案 0 :(得分:0)
您正在将category.catid varchar(16)与items.catid int(11)进行比较 如果比较 int = int ,会更快 推断出catid只是数字,你可以尝试改变类别表中的catid列
alter table category modify column catid int(11) NOT NULL;
测试上面的代码。
注意:如果您有任何category.catid大于 2147483647 ,您必须 改为bigint而不是int。
如果两个catid not null ,我可以理解没有catid没有itens,那么你可以改变 LEFT JOIN项目i on i.catid = c.catid 由 INNER JOIN项目i ON i.catid = c.catid 我不确定这会更快,但尝试一下。
理想是catid是category和items.catid的一个外键的category.catid的主键。但要执行此操作,您需要删除主键到category.id并添加到category.catid后,可以添加外键items.catid。但只是比较int = int会有所不同。