我有这样的表:
| 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 |
此查询的响应正确,但速度太慢了!
我想知道是否有更快的计算方法? 我很感谢你的指导。
答案 0 :(得分:3)
您的查询看起来并不太糟糕。我认为你的问题是缺乏适当的索引。
如果您只是在reagent
列上添加索引,它应该更快地运行:
CREATE INDEX mytb_reagent_ix ON mytb(reagent);
确认查询执行速度最快的最简单方法是使用EXPLAIN statement查看执行计划,并确保主键或辅助键用于所有查询步骤 - 我在此处为您执行了此操作{ {3}}
答案 1 :(得分: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