-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 に答える