我正在计算下表中每个id的匹配行数尽管有一个选项是创建另一个表来跟踪每个类别的计数,但我更希望在不创建第二个表的情况下解决这个问题(最好也不创建临时表)。
我的桌子:

+---------+----------------+
| id      | category       |
+---------+----------------+
| 3611383 | AAAAAAAAAAAAAA |
| 3611382 | AAAAAAAAAAAAAA |
| 3611381 | AAAAAAAAAAAAAA |
| 3611378 | AAAAAAAAAAAAAA |
| 3611377 | AAAAAAAAAAAAAA |
| 3611376 | AAAAAAAAAAAAAA |
| 3611374 | AAAAAAAAAAAAAA |
| 3611373 | AAAAAAAAAAAAAA |
| 3611372 | BBBBBBBBBBBBBB |
| 3611371 | BBBBBBBBBBBBBB |
| 3611370 | BBBBBBBBBBBBBB |
| 3611369 | BBBBBBBBBBBBBB |
| 3611366 | CCCCCCCCCCCCCC |
| 3611365 | CCCCCCCCCCCCCC |
| 3611364 | CCCCCCCCCCCCCC |
+---------+----------------+

期望输出:
+---------+----------------+---------+
| id      | category       | count   |
+---------+----------------+---------+
| 3611383 | AAAAAAAAAAAAAA | 8       |
| 3611382 | AAAAAAAAAAAAAA | 8       |
| 3611381 | AAAAAAAAAAAAAA | 8       |
| 3611378 | AAAAAAAAAAAAAA | 8       |
| 3611377 | AAAAAAAAAAAAAA | 8       |
| 3611376 | AAAAAAAAAAAAAA | 8       |
| 3611374 | AAAAAAAAAAAAAA | 8       |
| 3611373 | AAAAAAAAAAAAAA | 8       |
| 3611372 | BBBBBBBBBBBBBB | 4       |
| 3611371 | BBBBBBBBBBBBBB | 4       |
| 3611370 | BBBBBBBBBBBBBB | 4       |
| 3611369 | BBBBBBBBBBBBBB | 4       |
| 3611366 | CCCCCCCCCCCCCC | 3       |
| 3611365 | CCCCCCCCCCCCCC | 3       |
| 3611364 | CCCCCCCCCCCCCC | 3       |
+---------+----------------+---------+

我最近得到的是
SELECT id, category, count(category) AS c FROM mytable ORDER BY id DESC;

但这只会产生一行:
+---------+----------------+---------+
| id      | category       | c       |
+---------+----------------+---------+
| 3611383 | AAAAAAAAAAAAAA | 8       |
+---------+----------------+---------+

最佳答案

一种方法是关联子查询:

select t.*,
       (select count(*) from mytable t2 where t2.category = t.category) as c
from mytable t;

另一种方法是做group byjoin。相关子查询的一个优点是它可以很容易地利用mytable(category)上的索引。

关于mysql - 选择MySQL中特定列的匹配行数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46840718/

10-10 00:12