简体   繁体   中英

MySQL SELECT MIN row of INNER JOINed table

This is what I have currently (cut down a little):

SELECT *, item_prices.price AS minPrice
    FROM items  
    LEFT JOIN item_details USING(item_id) 
    LEFT JOIN item_prices USING(item_id) 
WHERE 1=1
GROUP BY item_id;

My issue is that item_prices may match more than one row for each item - I only want to get the row with the minimum value of price . I've been looking around SO and the web for similar questions but I'm feeling a bit out of my depth here, can anyone help?

You should use query:

SELECT *, MIN(item_prices.price) AS minPrice
    FROM items  
    LEFT JOIN item_details USING(item_id) 
    LEFT JOIN item_prices USING(item_id) 
WHERE 1=1
GROUP BY item_id;

Replace your join to item_prices with a join to a subquery which gets the minimum price for each item:

left join (select item_id, min(price) price group by item_id) minprice using (item_id)

I don't usually use MySQL, but I believe that syntax is valid. It might need tweaking.

You could do this with a subquery, along the lines of:

SELECT *, 
    (SELECT 
        MIN(item_price) 
     FROM 
        item_prices inner 
     WHERE inner.item_id = items.item_id) AS minPrice 
FROM items

GROUP BY item_id; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM