在MySQL中使用大数据进行慢计数查询

时间:2014-08-16 05:32:08

标签: mysql

我有三张桌子

id
name

产品

id
name
point_id

验证

id
name
product_id
result

当我创建产品时,我需要给它一点,在我验证产品后,我会将结果保存在验证表中,现在我的客户想要运行点来计算点的每个不同验证结果,&# 39;我是怎么做的。

SELECT `p`.`name`,
(SELECT COUNT(`pr`.`id`) FROM `products` `pr` INNER JOIN `verifies` `v` ON `pr`.`id' = `v`.`product_id` WHERE `pr`.`point_id` = `p`.`p_id` AND `v`.`result` = 1) AS `verify_result1`,
(SELECT COUNT(`pr`.`id`) FROM `products` `pr` INNER JOIN `verifies` `v` ON `pr`.`id' = `v`.`product_id` WHERE `pr`.`point_id` = `p`.`p_id` AND `v`.`result` = 2) AS `verify_result2`,
(SELECT COUNT(`pr`.`id`) FROM `products` `pr` INNER JOIN `verifies` `v` ON `pr`.`id' = `v`.`product_id` WHERE `pr`.`point_id` = `p`.`p_id` AND `v`.`result` = 3) AS `verify_result3`,
(SELECT COUNT(`pr`.`id`) FROM `products` `pr` INNER JOIN `verifies` `v` ON `pr`.`id' = `v`.`product_id` WHERE `pr`.`point_id` = `p`.`p_id` AND `v`.`result` = 4) AS `verify_result4`,
(SELECT COUNT(`pr`.`id`) FROM `products` `pr` INNER JOIN `verifies` `v` ON `pr`.`id' = `v`.`product_id` WHERE `pr`.`point_id` = `p`.`p_id` AND `v`.`result` = 5) AS `verify_result5`
FROM `points` `p`

结果是正确的,但它非常慢,因为积分表有超过3000个数据,如何让它更快?

2 个答案:

答案 0 :(得分:1)

SELECT `p`.`name`,
  COUNT( IF( `v`.`result` = 1, 1, NULL ) ) As Result1,
  COUNT( IF( `v`.`result` = 2, 1, NULL ) ) As Result2,
  COUNT( IF( `v`.`result` = 3, 1, NULL ) ) As Result3,
  COUNT( IF( `v`.`result` = 4, 1, NULL ) ) As Result4,
  COUNT( IF( `v`.`result` = 5, 1, NULL ) ) As Result5,
FROM `points` `p`
  INNER JOIN `products` `pr` ON `p`.`p_id` = `pr`.`point_id`
  INNER JOIN `verifies` `v` ON `pr`.`id' = `v`.`product_id`
GROUP BY `p`.`name`

答案 1 :(得分:0)

您也可以使用SUM代替COUNT,例如:

SELECT `p`.`name`
        , SUM(IF(result=1,1,0)) as verify_result1
        , SUM(IF(result=2,1,0)) as verify_result2
        , SUM(IF(result=3,1,0)) as verify_result3
        , SUM(IF(result=4,1,0)) as verify_result4
        , SUM(IF(result=5,1,0)) as verify_result5
FROM points p
INNER JOIN products pr ON p.id = pr.point_id
INNER JOIN verifies v ON pr.id = v.product_id
GROUP BY p.name