Mysql – pass selected variable value to inside select query MySQL

MySQL

i have two tables connected with one to many relationship. i have to sort parent table data according to child table data.

tables :

product
---------------------------
|id | name | default_price |
---------------------------

variant
-----------
|id | name| 
-----------


product_stock
------------------------------------------------
|id | product_id | variant_id | price |available 
------------------------------------------------

one product can have many product_stock rows.

I just need to sort product by product_stock minimum price

here what i did:

SELECT id,(SELECT price FROM `product_stock`
             WHERE product_id = 1
             ORDER By price LIMIT 1) as price
    from product ORDER BY price

this is working for only product id 1 . i need to pass dynamically selected product id to it . is this possible? thank you

Best Answer

SELECT product.*
FROM product
JOIN ( SELECT product_id id, MIN(price) price
       FROM product_stock
       GROUP BY 1 ) min_prices USING (id)
ORDER BY min_prices.price

If some products are absent in product_stock they won't be listed. If you need in them then use LEFT JOIN.

Related Question