tags:

views:

62

answers:

5

hi i have a table as follows id,school,address,city,state,phone,email,fax . There is almost 40 cities . I need to select 1 entry from each city. can any one guide me

example

city 

 a1     30 entries

 a2     12 entries

......
 a40    36 entries

 Pick 1 from each a1,a40
A: 
select * from your_table_name group by state, city

and with a Random select

select * from your_table_name group by state, city order by rand()
gurun8
in **mysql** this is the simplest and shortest of answer to the question. +1 to counter the downvoter(s)!
knittl
+2  A: 
select * 
  from table_name 
 where id in (  select MAX(id) 
                  from table_name 
              group by city
             )
Salil
Why did this get a down vote? Sigh .. a bit crude but looks like it should work!
lexu
Yes i agree with @lexu
Aditya
Just removed my downvote, it was previously invalid syntax.
Michael
A: 

in mysql you can simply say:

select * from table group by city
knittl
I don't think that is a good idea: http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html
Mark Byers
@mark byers: so where is the problem? the page talks about standard sql. i clearly stated i'm talking about mysql, and afaik in mysql it is possible to select columns without aggregating them. the row you get is unspecified, but you get values …
knittl
@knittl: It says there "When using this feature, all rows in each group should have the same values for the columns that are ommitted from the GROUP BY part." That is not the case here.
Mark Byers
@mark byers, quote wars! it also says »The server is free to return any value from the group, so the results are indeterminate unless all values are the same.« he wants to select any single row, _randomly_. indeterminate comes close to randomly (apart from the fact, that mysql always returns the first row found)
knittl
@mark byers, have you actually tried to run such a query in mysql?
knittl
+4  A: 

In general I prefer to tackle these cases with a JOIN to a sub query, as in the following example:

SELECT    s.id, s.school, s.address, s.city, s.phone, s.email, s.fax
FROM      schools s
JOIN      (SELECT   MAX(id) as max_id
           FROM     schools
           GROUP BY city) sub_s ON (sub_s.max_id = s.id);

The JOIN is practically restricting your result set to entries with distinct cities. This is also assuming that you want to select the entry with the highest id when you have multiple entries for each city. If you prefer to choose the lowest id, you can use the MIN() aggregate function in the sub query instead of MAX().

Daniel Vassallo
+1 for the explanation, worth much more than the query alone.
lexu
A: 

SELECT DISTINCT city FROM tablename

poeschlorn