嵌套的选择查询 - mysql sakila数据库

时间:2016-03-22 04:37:43

标签: mysql

我找到了每个区的最小postode,现在想要找到所有这些区邮政编码最小值的最大值。我一直坚持如何做到最大,同时保持其他部分的机智。

select 
   district, 
   postal_code, 
   min(postal_code) from address
group by district
having district is not null and district !="" and postal_code>0
order by district;

result

1 个答案:

答案 0 :(得分:1)

如果只需要max(min_postal_code),请使用以下语句。

select max(min_postal_code) 
from (
    select district, min(postal_code) AS min_postal_code
    from address
    where district is not null and district !="" and postal_code>0
    group by district
    order by district) t

如果还需要带有MAX(min_postal_code)的地区名称。请使用以下语句。

select * 
from (select district, min(postal_code) AS min_postal_code
    from address
    where district is not null and district !="" and postal_code>0
    group by district) t
where t.min_postal_code = 
(
    select max(min_postal_code) 
    from (select district, min(postal_code) AS min_postal_code
        from address
        where district is not null and district !="" and postal_code>0
        group by district) t2
);