MySQL finding the most expensive in each zip code

前端 未结 4 415
盖世英雄少女心
盖世英雄少女心 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:19

    Something like this:

    SELECT name,price,zip_code
    FROM products
    WHERE state='NJ' AND price=(SELECT MAX(price) FROM products)
    
    0 讨论(0)
  • SELECT
          t.name, t.city, t.zip_code, t.price
    FROM  
           ( SELECT zip_code
                  , MAX(price) as price 
             FROM products 
             WHERE state = 'NJ' 
             GROUP BY zip_code
           ) AS tm 
        JOIN
            products as t
                ON  tm.zip_code = t.zip_code 
                AND tm.price = t.price
    WHERE 
            t.state = 'NJ' 
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-22 07:41

    This should work, though I can't vouch for it's efficiency. Per comment, here's an update that pulls back all records with price equal to the max price per zip code.

    SELECT *
      FROM products p1
     WHERE p1.state = 'NJ'
       AND p1.price = (select max(price) from products p2
                       where p1.zip_code = p2.zip_code)
    

    http://www.sqlfiddle.com/#!2/98f6d/2

    0 讨论(0)
提交回复
热议问题