Sachin Vairagi
Sachin Vairagi

Reputation: 5334

mysql lowest and highest value with join

I have two tables :

mysql> SELECT * FROM master_products; +----+-------+ | id | name | +----+-------+ | 1 | row1 | | 2 | row2 | | 3 | row3 | | 4 | row4 | +----+-------+

AND

mysql> SELECT * FROM products; +----+---------+-------+ | id | masterid | cost | +----+---------+-------+ | 1 | 1 | 1000 | | 2 | 1 | 1050 | | 3 | 2 | 1020 | | 4 | 2 | 999 | | 4 | 3 | 899 | +----+-------+---------+

I want to select all product from master table with highest and lowest cost from product table, but when i am using mysql min, max function then it is not returning all products, here is my query :

SELECT master_products.id,name, MIN(cost) AS LowestCost, MAX(cost) AS HighestCost FROM master_products JOIN product ON product.masterid= master_products.id

Is there any way to get this by single query? desired output :

+----+------------+------------+--------------+ | id | name | LowestCost | HighestCost | +----+-------------+------------+--------------+ | 1 | row1 | 1000 | 1050 | | 2 | row2 | 999 | 1020 | | 3 | row3 | 899 | 899 | | 4 | row4 | NA | NA | +----+-------+-----------+------+--------------+

Upvotes: 1

Views: 118

Answers (1)

igorshmigor
igorshmigor

Reputation: 802

Use a left join:

SELECT master_products.id, master_products.name, MIN(cost) AS LowestCost, MAX(cost) AS HighestCost 
FROM master_products 
LEFT JOIN `products` ON `products`.`masterid`= `master_products`.`id`
GROUP BY master_products.id

Upvotes: 1

Related Questions