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
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.