简体   繁体   English

MySQL的最低和最高价值与联接

[英]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 : 我想从主表中选择具有最高和最低成本的所有产品,但是当我使用mysql min,max函数时,它不会返回所有产品,这是我的查询:

SELECT master_products.id,name, MIN(cost) AS LowestCost, MAX(cost) AS HighestCost FROM master_products JOIN product ON product . SELECT master_products.id,名称,MIN(成本)AS最低成本,MAX(成本)AS HighestCost FROM master_products JOIN product ON product masterid = master_products . 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 | +----+-------+-----------+------+--------------+

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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