I have tables like these:
INSERT INTO listings
(id, external_id, variation_id, product_id) VALUES
(101, '9900001', '9900001var1', 1),
(102, '9900001', '9900001var2', 4),
(103, '9900002', '9900002var1', 1),
(104, '9900002', '9900002var2', 2),
(105, '9900003', '9900003var1', 3),
(106, '9900003', '9900003var2', 4);
INSERT INTO products
(id, price) VALUES
(1, 101),
(2, 100),
(3, 100),
(4, 102);
Which means that there are 3 listings (9900001, 9900002, 9900003) with 2 products each (1, 4), (1, 2) and (3, 4) respectively.
What I need is to retrieve one single row for each listing, with the id (not the price) of the product with the highest price in that listing.
So, the desired output would be:
id | external_id | variation_id | product_id
[ANY] 9900001 [ANY] 4
[ANY] 9900002 [ANY] 1
[ANY] 9900003 [ANY] 4
The closest I got to the desired answer was with this query:
SELECT
p.id AS product_id_max,
p.price AS product_price_max,
MAX(p.price) AS product_price_max_max,
listings.*
FROM listings
INNER JOIN (
-- Subquery tested above:
SELECT DISTINCT pp3.* FROM
(SELECT MAX(p2.price) as max_price
FROM products p2
INNER JOIN listings l2 ON l2.product_id = p2.id
GROUP BY l2.external_id) pp2
INNER JOIN
(SELECT p3.* FROM products p3 ) pp3
ON
pp2.max_price = pp3.price
ORDER BY pp3.price DESC
) AS p
ON p.id = listings.product_id
-- WHERE MAX(p.price) = p.price
GROUP BY external_id
-- HAVING MAX(p.price) = p.price
ORDER BY product_price_max DESC
Uncommenting the WHERE clause throws an error, uncommenting the HAVING clause returns less rows than desired. Leavin both commented give the correct rows but wrong values in the product_id column.