计算重复值 - 帮助我的mysql查询死得很慢

时间:2013-07-23 14:07:56

标签: mysql sql performance

假设我有一张这样的表:

Id*|value

对于每个Id,我想计算相应的value存在多少次。与此示例数据一样:

1, a
2, b
3, a 
4, b
5, c
6, a

我想:

1, a, 3
2, b, 2
3, a, 3
4, b, 2
5, c, 1
6, a, 3

这就是我现在所拥有的,我相信它正在发挥作用,但它已经过时了:

SELECT t1.Id, t1.value, COUNT(t2.value) FROM `table` AS t1
LEFT JOIN `table` AS t2 ON (t1.value = t2.value)
GROUP by t1.Id

我的表包含数千行的数据。关于如何改善这种表现的任何建议?

3 个答案:

答案 0 :(得分:1)

试试这个

SELECT t1.Id, t1.value, t2.cnt FROM Table1 AS t1
INNER JOIN 
(
  SELECT value, COUNT(value) as cnt 
    FROM Table1 GROUP BY value
) AS t2 ON (t1.value = t2.value)
ORDER BY t1.Id

OR

SELECT t1.id,t1.value,COUNT(t2.id) AS cnt FROM Table1 AS t1
INNER JOIN Table1 AS t2
   ON  t1.value = t2.value
GROUP BY t1.id,t1.value
ORDER BY t1.id

答案 1 :(得分:1)

左边连接它自己运行GROUP BY查询:

SQL小提琴 - http://sqlfiddle.com/#!2/5b8f5/18

SELECT 
   tbl.id, tbl.value, cnts.counts FROM tbl
LEFT JOIN ( 
   SELECT value, COUNT(value) AS counts FROM tbl GROUP BY value
) AS cnts ON (tbl.value = cnts.value)

答案 2 :(得分:0)

SELECT t1.Id, t1.value, t2.value FROM `table` AS t1
LEFT JOIN 
    (Select value, COUNT(value)` as value 
    from table` group by value) AS t2 
   ON      (t1.value = t2.value)
GROUP by t1.Id