MySQL finding the most expensive in each zip code

前端 未结 4 423
盖世英雄少女心
盖世英雄少女心 2021-01-22 06:36

I have a table called Products with the schema (name, city, state, zip_code price).

And I want to find the most expensive products\' name for a given state\'s each zip_c

4条回答
  •  面向向阳花
    2021-01-22 07:35

    I think that you will (either way) need a composite index on products.state,products.zip_code.

    Try the following:

    SELECT p.zip_code, MAX(p.price) AS max_price, 
    (
      SELECT GROUP_CONCAT(CAST(products.id AS CHAR)) FROM products 
      WHERE products.state = 'NJ' AND 
      products.zip_code = p.zip_code AND products.price = MAX(p.price) 
    ) AS product_ids
    FROM products p WHERE p.state = 'NJ' GROUP BY p.zip_code ORDER BY NULL
    

    Note:
    GROUP_CONCAT has a limitation regarding the maximum length of the resulting string, see http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_group_concat_max_len . If you are missing some IDs, this could be the reason.

提交回复
热议问题