2013-03-02 57 views
-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) 
+0

請解釋你做了什麼來得到這個結果。 – smartmeta 2013-03-02 08:29:47

回答

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

這裏的SQLfiddle鏈接。

相關問題