I have two tables. The first table shows the id_product and product_price_value. Below I will show you one example (in my database there are many rows)
TABLE: main_product
ID_product: product_price_value:
119, Product1
TABLE: 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).
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.
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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.