I have this query (notice that all 3 subqueries are selecting different columns from the same row). Essentially I want to get the rows in product_bid with the maximum date alongside the product row.
SELECT
p.product_id,
p.product_title,
(SELECT b.bid_id FROM product_bids b WHERE b.bid_product_id=p.product_id ORDER BY b.bid_date DESC LIMIT 1) AS bid_id,
(SELECT b.bid_date FROM product_bids b WHERE b.bid_product_id=p.product_id ORDER BY b.bid_date DESC LIMIT 1) AS bid_date,
(SELECT b.bid_amount FROM product_bids b WHERE b.bid_product_id=p.product_id ORDER BY b.bid_date DESC LIMIT 1) AS bid_amount
FROM product p
WHERE p.product_auction_id=325
Is there a way to do the subquery once to get the PK of product_bids, and join on that (the result of the subquery) or any clean way of doing this?
Side Note: Would the query optimiser recognise this anyway, making it less important?
Thanks
You can join your tables together with a subquery that selects the latest bid date for each product: