There are some problems in your sentence. First I will put as it is corrected, then I will 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 I imagine you would like to do, which is to catch the district with the largest zip code (another subselect);
- I don’t know how Mysql manages tables
SELECT
nested, but it is clear to me that the scope of the nested table does not exist within WHERE
, so I nested twice using HAVING
, which is the condition of testing aggregation functions.
I tried running phpmyadmin and returned the following error: #1111 - Invalid use of group Function
– João Carlos
You’re right. I edited the answer.
– Leonel Sanches da Silva
Another problem occurred, it tries to fetch this sentence "select MAX(min_postal_code) from table" in the database and not in the one generated by the previous select which returns the following error: #1146 - Table 'sakila.table' doesn’t exist where sakila is the name of my base
– João Carlos
I modified it again. It didn’t look very nice, but it should work.
– Leonel Sanches da Silva
Thus ai does not return only one record but all the smallest ones of the address table, I could by the old code but does not return the name of District: SELECT District, MAX(table.min_postal_code) FROM (SELECT District, MIN(postal_code) as min_postal_code FROM address WHERE postal_code != ' GROUP BY District) table;
– João Carlos
Yes, you’re right. I’m just not testing your sentence, so it’s a little hard to imagine the way out. Look now.
– Leonel Sanches da Silva
Let’s go continue this discussion in chat.
– João Carlos