[英]Select only rows where min(column1) and min (column2)
I have two tables. 我有两张桌子。 The first table shows the id_product and product_price_value. 第一个表显示id_product和product_price_value。 Below I will show you one example (in my database there are many rows) 下面,我将向您展示一个示例(在我的数据库中,有很多行)
TABLE: main_product 表格:main_product
ID_product: product_price_value:
119, Product1
TABLE: value_product 表格:value_product
product_price_value: width_from: width_to: height_from: height_to: price:
Product1 , 10, 20, 5, 15, 100
Product1 , 10, 20, 10, 30, 200
Product1 , 20, 30, 5, 45, 300
Product1 , 30, 30, 20, 30, 400
As you can see one product can have multiple dimensions. 如您所见,一种产品可以具有多个尺寸。 I want to get the price with the lowest width and height combined. 我想获得宽度和高度最低的价格。 In my example it should be the first row (width from -> 10, height from -> 5). 在我的示例中,它应该是第一行(宽度从-> 10开始,高度从-> 5开始)。
I used the following code: 我使用以下代码:
$sql = "SELECT value_product.price FROM value_product INNER JOIN main_product
ON (main_product.product_price_value = value_product.product_price_value
AND (
value_product.width_from = (SELECT MIN(value_product.width_from) FROM value_product)
AND value_product.height_from = (SELECT MIN(value_product.height_from) FROM value_product)
)
);";
In this way I thought I was gonna get the price for the lowest width/height for each product. 这样,我想我将获得每种产品的最低宽度/高度的价格。 But the only results I get is when the width_from OR height_from contains a value of 0. If either width or height has more than 0 then it doesn't return anything. 但是,我得到的唯一结果是,当width_from或height_from包含值0时。如果width或height大于0,则它不返回任何值。
Am I doing something wrong in my query? 我在查询中做错了吗?
Is there any way to get the price with the lowest 'width_from' and 'height_from' columns? 有什么方法可以使“ width_from”和“ height_from”列的价格最低?
Thanks 谢谢
If you only want such a price for one product, you can simply sort and limit: 如果您只想为一种产品设置这样的价格,则可以简单地进行排序和限制:
SELECT price
FROM value_product
WHERE product_price_value = ?
ORDER BY width_from + height_from
LIMIT 1
Otherwise you're after the group-wise minimum , which can be obtained by joining the table back to a grouped version of itself: 否则,您将遵循按组的最小值 ,这可以通过将表重新连接到自身的分组版本来获得:
SELECT v.product_price_value,
v.price
FROM value_product v
JOIN (
SELECT product_price_value,
MIN(width_from + height_from) min_dimension
FROM value_product
GROUP BY product_price_value
) t
ON t.product_price_value = v.product_price_value
AND t.min_dimension = v.width_from + v.height_from
In both cases I have assumed that there is only ever one record with the minimal dimensions. 在这两种情况下,我都假定只有一个记录具有最小的尺寸。 Should there be multiple such records, the first query will pick one indeterminately; 如果有多个这样的记录,则第一个查询将不确定地选择一个; and the second query will list them all. 第二个查询将全部列出。 If this is not your desired behaviour, you will have to clarify what you would like to occur instead. 如果这不是您想要的行为,则必须澄清您希望发生的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.