您好我有一张表格如下 ID,学校,地址,城市,州,电话,电子邮件,传真。有近40个城市。我需要从每个城市中选择1个条目。任何人都可以指导我
例如
city
a1 30 entries
a2 12 entries
......
a40 36 entries
Pick 1 from each a1,a40
答案 0 :(得分:4)
一般情况下,我更喜欢通过JOIN到子查询来处理这些情况,如下例所示:
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);
JOIN
实际上将结果集限制为具有不同城市的条目。这也假设您希望在每个城市有多个条目时选择具有最高ID的条目。如果您希望选择最低ID,则可以在子查询中使用MIN()
聚合函数,而不是MAX()
。
答案 1 :(得分:2)
select *
from table_name
where id in ( select MAX(id)
from table_name
group by city
)
答案 2 :(得分:0)
select * from your_table_name group by state, city
并使用随机选择
select * from your_table_name group by state, city order by rand()
答案 3 :(得分:0)
select * from table group by city
答案 4 :(得分:0)
SELECT DISTINCT city FROM tablename