tags:

views:

32

answers:

3

I have a database which will receive a whole bunch of information, but most importantly it will receive a city name for each row. Sample below:

id         city
1          London
2          Manchester
3          London
4          Brighton
5          Oxford
6          Oxford
7          London

I want to SELECT only the city name from this table, displaying the top 3 results in the order of which occurs most often.

So far I am using the query below which I found:

SELECT N.city, COUNT(*) AS howmany
FROM ( SELECT DISTINCT city FROM events ) AS N,
events AS T
WHERE N.city = T.city
GROUP BY N.city
ORDER BY howmany
LIMIT 0,2 
+2  A: 

You can simplify your existing query to a single access to the events table, without needing to join it to itself:

SELECT N.city, 
       COUNT(N.city) AS howmany 
  FROM events AS N
 GROUP BY N.city 
 ORDER BY howmany 
 LIMIT 3

if you don't want to return the count, try:

SELECT N.city
  FROM events AS N
 GROUP BY N.city 
 ORDER BY COUNT(N.city)
 LIMIT 3
Mark Baker
er, `AS T` and then `N.___`?
Amber
spotted thanks.
Mark Baker
+1: Very nice to see someone using table aliases
OMG Ponies
@OMG Ponies: I use table aliases when I'm working with multiple tables, or if for some reason there's a conflict between column names and SQL names (which there shouldn't be, if you chose your columns properly), but for a single table with fields that don't conflict, they're sort of redundant.
Amber
@Amber: It's a very good habit to use table aliases, even if there's only one table in the query. If another table is joined, it's clear what column is being used. Given some people's formatting, it distinguishes column references. And it will help point out references that no longer exist if the table(s) are altered after the query. It's also good to be consistent in your codebase.
OMG Ponies
+2  A: 

You don't need the additional join GROUP BY will already take care of the DISTINCT aspect for you.

SELECT city, COUNT(*) AS howmany
FROM 
events
GROUP BY city
ORDER BY howmany DESC
LIMIT 0,3 
Martin Smith
+1: You corrected the LIMIT before I could :)
OMG Ponies
Yep - MySQL is a bit out of my comfort zone :-)
Martin Smith
+2  A: 

If you only want to have the 'city' field in your final result:

SELECT city FROM (
  SELECT city, COUNT(*) as ccount
  FROM events
  GROUP BY city
)
ORDER BY ccount DESC
LIMIT 3

If you don't care about the fields in the final result, as long as city is one of them, it's even simpler:

SELECT city, COUNT(*) as ccount
FROM events
GROUP BY city
ORDER BY ccount DESC
LIMIT 3
Amber