-1
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)
4

1 回答 1

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

这是SQLfiddle链接。

于 2013-03-02T08:32:43.640 回答