1

我有这样的表:

| ID | REAGENT |
|----|---------|
|  1 |       0 |
|  2 |       0 |
|  3 |       1 |
|  4 |       2 |
|  5 |       2 |
|  6 |       1 |
|  7 |       3 |
|  8 |       1 |
|  9 |       4 |
| 10 |       3 |
| 11 |       6 |
| 12 |       4 |
| 13 |       1 |
| 14 |       0 |
| 15 |       0 |
| 16 |       2 |
| 17 |      11 |
| 18 |      23 |
| 19 |      11 |
| 20 |       7 |
| 21 |       6 |
| 22 |      10 |
| 23 |       1 |
| 24 |      11 |
| 25 |      15 |
| 26 |       4 |

我使用此查询来计算同一表中“试剂”字段中每个“ID”字段的重复次数

  SELECT 
   b.ID,(SELECT count(a.reagent)FROM mytb AS a WHERE a.reagent=b.ID ) AS reagentCount 
FROM mytb AS b

| ID | REAGENTCOUNT |
|----|--------------|
|  1 |            5 |
|  2 |            3 |
|  3 |            2 |
|  4 |            3 |
|  5 |            0 |
|  6 |            2 |
|  7 |            1 |
|  8 |            0 |
|  9 |            0 |
| 10 |            1 |
| 11 |            3 |
| 12 |            0 |
| 13 |            0 |
| 14 |            0 |
| 15 |            1 |
| 16 |            0 |
| 17 |            0 |
| 18 |            0 |
| 19 |            0 |
| 20 |            0 |
| 21 |            0 |
| 22 |            0 |
| 23 |            1 |
| 24 |            0 |
| 25 |            0 |
| 26 |            0 |

这个查询有一个正确的响应,但是太慢了!

我想知道是否有更快的计算方法?我很感谢你的指导。

4

2 回答 2

3

您的查询看起来还不错。我认为您的问题是缺乏适当的索引。

如果您只是在reagent列上添加索引,它应该工作得更快:

CREATE INDEX mytb_reagent_ix ON mytb(reagent);

确认您的查询是否快速执行的最简单方法是使用EXPLAIN 语句查看执行计划,并确保所有查询步骤都使用主键或辅助键 - 我在这个SQLFiddle Demo中为您做了。

于 2013-11-10T22:44:23.637 回答
1

这应该适合你:

SELECT COUNT(*) AS repetitions, REAGENT FROM mytb GROUP BY REAGENT

您甚至可以按重复次数排序,以首先查看重复次数最多的那些:

SELECT
COUNT(*) AS repetitions, REAGENT

FROM
mytb

GROUP BY
REAGENT

ORDER BY
repetitions DESC
于 2013-11-10T22:05:20.690 回答