显示全部和计数重复MySQL

时间:2015-06-11 10:15:36

标签: mysql count group-by

我有这张桌子:

id   name  
1    AAA
2    BBB
3    BBB
4    BBB
5    AAA
6    CCC

我怎么能得到这个?

id   name  count
1    AAA     2
2    BBB     3
3    BBB     3
4    BBB     3
5    AAA     2
6    CCC     1

我想计算重复项(名称),获取所有行,而不对其进行分组。

谢谢。

3 个答案:

答案 0 :(得分:1)

您可以使用相关子查询:

SELECT id, name, (SELECT COUNT(*)
                  FROM mytable AS t1
                  WHERE t1.name = t2.name) AS cnt
FROM mytable AS t2       

Demo here

答案 1 :(得分:0)

select t1.id, t1.name, t2.cnt
from your_table t1
join
(
  select name, count(*) as cnt
  from your_table
  group by name
) t2 on t1.name = t2.name

答案 2 :(得分:0)

SELECT id, name, (SELECT COUNT(*)
                  FROM demo AS table1
                  WHERE table1.name = table2.name) 
    AS count
FROM demo AS t2