tags:

views:

137

answers:

4

Two tables:

table_a
-------
table_a_id: (primary, int)

table_b
-------
table_a_id: (index, int, from table_a)
table_b_value: (varchar)

A one to many relationship between table_a_id and table_b_value.

Given a query like this:

SELECT DISTINCT(table_a_id) FROM table_a 
JOIN table_b ON table_a.table_a_id=table_b.table_a_id

I want to order by the number of occurrences of table_a_id in table_b. I'm not really sure how to write this in MySQL.

+4  A: 
SELECT COUNT(table_b.table_a_id) AS count 
FROM table_a 
JOIN table_b ON table_b.table_a_id = table_a.id 
GROUP BY table_b.table_a_id 
ORDER_BY count DESC 
Kemo
Well that would give me the total count, but I don't think it wouldn't order the query by the total count, which is what I want to do.
Finbarr
I updated the post, look now ( didn't notice last few lines of your question )
Kemo
Nothing short of glorious.
Finbarr
IDs in table A that don't appear in table B won't be counted in the result. Use a left join, group by `table_a.id` and count `table_a.id` to resolve this.
outis
@outis I think @Finbarr asked for "number of occurrences of table_a_id in table_b" :)
Kemo
@Kerno: if a table_a_id doesn't appear in table_b, it occurs 0 times; that a given table_a_id doesn't appear in table_b doesn't mean it shouldn't appear in the result of the count query. I confess the formulation of the question is ambiguous enough that either interpretation could be the correct one. If we take "table_a_id" to mean "table_a.table_a_id", then the result should include those IDs occuring 0 times; if "table_a_id" refers to "table_b.table_a_id", then the result shouldn't include them (in which case the join is unnecessary).
outis
A: 

Why do you need to join the tables at all in this case?

SELECT table_a_id FROM table_b GROUP BY table_a_id order by count(table_a_id) desc
matthewh
Because `count(table_a.table_a_id)` will always be 1, and Finbarr wants the count for `table_b.table_a_id`.
outis
Whoops - typo from me - post edited (should have been FROM table_b)
matthewh
That's better. However, IDs from table A that don't appear in table B won't appear in the result. The currently accepted answer has the same issue.
outis
+1  A: 

Hey. Try something like:

SELECT 
        a.table_a_id,
        COUNT(b.table_a_id) AS `a_count`
FROM    table_a AS a
LEFT JOIN   table_b AS b
    ON  a.table_a_id = b.table_a_id
GROUP BY a.table_a_id
ORDER BY `a_count`
Atli
A: 

Using your example

SELECT table_a_id, COUNT(*)
FROM table_b
GROUP BY table_a_id

A real world example

If you want a table like:

post_id  comments_count
1        20
2        125
3        43

If you might need other information from the A table, you can:

select p.id, count(c.*) comments_count
from posts p
join comments c on c.post_id = p.id
group by p.id

If you don't need anything from the A table, you can simplify:

select post_id, count(*)
from comments
group by post_id
macek