Select nested Mysql

Asked

Viewed 5,098 times

1

I’m trying to get the most value out of 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

1 answer

1


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 SELECTnested, 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

  • You’re right. I edited the answer.

  • 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

  • I modified it again. It didn’t look very nice, but it should work.

  • 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;

  • Yes, you’re right. I’m just not testing your sentence, so it’s a little hard to imagine the way out. Look now.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.