Select Nested MySQL

1

I'm trying to get the highest value from the smallest of a table, the query I'm trying to execute is as follows:

SELECT district FROM
    (SELECT district, MIN(postal_code)
    FROM address
    WHERE postal_code != ''
    GROUP BY district)
WHERE MAX(postal_code);
  

Error: # 1248 - Every derived table must have its own alias

    
asked by anonymous 15.10.2015 / 00:17

1 answer

1

You have some problems with your sentence. First I'll post how it gets corrected, then I'll explain:

SELECT district FROM
  (SELECT district, min_postal_code from
    (SELECT district, MIN(postal_code) as min_postal_code
    FROM address
    WHERE postal_code != ''
    GROUP BY district) tabela
   GROUP BY district
   HAVING min_postal_code = MAX(min_postal_code)) tabela2;
  • Subselects need to be identified by a name. In this case, I used tabela ;
  • Aggregation functions, such as MIN , do not return good column names. So I used as min_postal_code ;
  • WHERE requires some test condition. Only MAX(postal_code) does not test anything. I put the test that I imagine you would like to do, which is to get the district with the highest zip code (another subselect);
  • I do not know how MySQL manages nested%% tables, but it is clear to me that the nested table scope does not exist within SELECT , so I nested twice using WHERE , which is the tests aggregation functions.
15.10.2015 / 00:51