views:

45

answers:

2

Hi all,

I'm having some difficulties with a query:

SELECT d.*, 
       (SELECT COUNT(id) FROM downloads WHERE category = d.category) AS count 
FROM downloads d 
GROUP BY d.category 
ORDER BY count DESC

So, I'm trying to get the total downloadcount of each category but this query hangs each time I run it.

The downloads table has +- 20000 rows

What am I doing wrong?

+3  A: 
SELECT category, count(id) as count
FROM downloads d 
GROUP BY d.category 
ORDER BY count DESC
Femaref
Ding ding ding we have a winner.
Dustin Fineout
This will fail, if you're projecting all the columns (d.*) you'd have to group by all the columns as well.
Ricardo Villamil
Oh man, I feel so stupid :) THX
Bundy
bad copy pasta. sorry
Femaref
@Ricardo Villamil: Unless category is unique.
Mark Byers
A: 

I think you'd be better off doing this:

  SELECT category, count(*) as cnt
    FROM downloads
GROUP BY category
ORDER BY cnt desc;
Ricardo Villamil