如何查找计数最多的对象数?

时间:2013-03-02 08:28:04

标签: mysql

create table foos (id, val1, ...)

create table bars (id, foo_id, val2. ...)

insert into foos (1, 1, ..)

insert into foos (2, 2, ..)

insert into foos (3, 3, ..)

insert into bars (1, 1, 1, ..)

insert into bars (2, 1, 1, ..)

insert into bars (3, 1, 1, ..)

insert into bars (4, 2, 1, ..)

insert into bars (5, 2, 1, ..)

insert into bars (6, 2, 1, ..)

insert into bars (7, 2, 1, ..)

insert into bars (8, 3, 1, ..)

我想计算这样的条形图,我应该如何按递减计数顺序进行计算

2, 4 (foo 2 has 4 bars)

1, 3 (foo 1 has 3 bars)

3, 1 (foo 3 has a bar)

1 个答案:

答案 0 :(得分:1)

SELECT `foo_id`, COUNT(1) AS `count`
FROM `bars`
GROUP BY `foo_id`
ORDER BY `count` DESC

以下是SQLfiddle链接。