Answer the question
In order to leave comments, you need to log in
How to join rows from another table with minimum value?
Given:
1) Products tableproduct
| id | title |
| 1 |продукт 1|
| 2 |продукт 2|
supplier_price
|product_id|supplier_id|price|
| 1 | 1 | 10 |
| 1 | 2 | 5 |
| 2 | 1 | 15 |
|product_id|supplier_id|price| id | title |
| 1 | 2 | 5 | 1 |продукт 1|
| 2 | 1 | 15 | 2 |продукт 2|
SELECT
supplier_product.product_id,
supplier_product.supplier_id,
MIN(supplier_product.price)
FROM product
LEFT JOIN supplier_product ON product.id = supplier_product.product_id
group by supplier_product.product_id, supplier_product.supplier_id
#group by supplier_product.product_id
SELECT
product.*,
min_price
FROM product
LEFT JOIN (
SELECT
supplier_product.product_id,
MIN(supplier_product.price) AS min_price
FROM supplier_product
GROUP BY supplier_product.product_id
) AS sp
ON product.id = sp.product_id
Answer the question
In order to leave comments, you need to log in
SELECT `p`.`product_id`, `p`.`supplier_id`, `p`.`price`, `i`.`title`
FROM (
SELECT `product_id`, MIN(`price`) AS `price`
FROM `supplier_price`
GROUP BY `product_id`
) AS `mp`
JOIN `supplier_price` AS `p` ON `p`.`product_id` = `mp`.`product_id`
AND `p`.`price` = `mp`.`price`
JOIN `product` AS `i` ON `i`.`id` = `mp`.`product_id`
SELECT `p`.`product_id`, `p`.`supplier_id`, `p`.`price`, `i`.`title`
FROM (
SELECT `product_id`, `supplier_id`, `price`
FROM `supplier_price`
GROUP BY `product_id`, `supplier_id`, `price` WITH ROLLUP
HAVING `price` = MIN(`price`)
) AS `p`
JOIN `product` AS `i` ON `i`.`id` = `mp`.`product_id`
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question