COUNT的性能缓慢

时间:2014-07-24 08:07:43

标签: mysql sql count

我在MySQL工作,想要计算购买特定产品的人数。因此,我使用以下查询:

SELECT o.pid AS person, a.article_group_id AS ag, COUNT(o.pid) AS my_count
FROM vda.clustering c
LEFT JOIN vda.orders o ON c.pid=o.pid
LEFT JOIN vda.articles a ON o.aid=a.id
WHERE c.cluster=1 AND c.cluster_round='0'
GROUP BY person, ag

输出正确,但检索此表需要8秒钟。

person  ag  my_count
1       1   1
7       0   3
13      0   2
13      7   2
...

如果我不计算数字,但只是使用下面的查询检索数据,则只需1秒钟。是否有其他语法我不知道加速计数?

SELECT o.pid AS person, a.article_group_id AS ag
FROM vda.clustering c
LEFT JOIN vda.orders o ON c.pid=o.pid
LEFT JOIN vda.articles a ON o.aid=a.id
WHERE c.cluster=1 AND c.cluster_round=0

person  ag  
1       1
7       0
7       0
7       0
13      7
13      16
13      36
13      11
13      16
...

编辑:补充信息:

我的表格是使用以下查询创建的。这些文章包含有关产品的信息。订单将人们与他们购买的物品结合在一起。我有单独的表格(此处未显示),其中我将brand_id翻译成适当的品牌。

"CREATE TABLE `persons` ("
"  `id` int(8) NOT NULL, "
"  `first_name` varchar(64), "
"  `last_name` varchar(64), "
"  `email` varchar(64) NOT NULL, "
"  `gender` enum('M','F','U') NOT NULL, "
"  `birthday` date, "
"  PRIMARY KEY (`id`), "
"  UNIQUE KEY (`email`) "
") AUTO_INCREMENT = 0, ENGINE=InnoDB")

TABLES['articles'] = (
"CREATE TABLE `articles` ("
"  `id` int(8) NOT NULL, "
"  `article_nr` varchar(20) NOT NULL, "
"  `article_group_id` int(8) NOT NULL, "
"  `brand_id` int(8) NOT NULL, "
"  PRIMARY KEY (`id`), " 
"  UNIQUE KEY (`article_nr`), "
"  FOREIGN KEY (`article_group_id`) REFERENCES `article_groups` (`id`), "
"  FOREIGN KEY (`brand_id`) REFERENCES `brands` (`id`) "
") ENGINE=InnoDB")

TABLES['orders'] = (
"CREATE TABLE `orders` ("
"  `id` int(11) NOT NULL, "
"  `date` date, "
"  `pid` int(8) NOT NULL, "
"  `aid` int(8) NOT NULL, "
"  `price` float NOT NULL, "
"  `discount` float NOT NULL, "
"  PRIMARY KEY (`id`), "
"  FOREIGN KEY (`pid`) REFERENCES `persons` (`id`), "
"  FOREIGN KEY (`aid`) REFERENCES `articles` (`id`) "
") ENGINE=InnoDB")

TABLES['clustering'] = (
"CREATE TABLE `clustering` ("
"  `pid` int(8) NOT NULL, "
"  `cluster` int(8), "
"  `cluster_round` varchar(32), "
"  PRIMARY KEY (`pid`, `cluster_round`), "
"  FOREIGN KEY (`pid`) REFERENCES `persons` (`id`) "
") ENGINE=InnoDB")

具有集群索引的执行计划,cluster_round,如评论中所述:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  c   ref cluster_ci  cluster_ci  103 const,const 24624   "Using where; Using index; Using temporary; Using filesort"
1   SIMPLE  o   ref order_pid   order_pid   4   vda.c.pid   1   NULL
1   SIMPLE  a   eq_ref  PRIMARY PRIMARY 4   vda.o.aid   1   NULL

0 个答案:

没有答案