MySQL select statement with MIN
I have two tables in a MySQL database. Products and product items. Products contains fields product_id, p开发者_开发技巧roduct_name, image. Product item contains field item_id, product_id, size_id, doq_id, price.
There are many product items for one product.
How do I write a statement which returns the lowest price for each product?
I have the following:
SELECT p.product_name, p.image, p.product_id, MIN(pi.price) AS price
FROM (`product_items` as pi, `product` as p)
WHERE `pi`.`product_id` = 'p.product_id'
GROUP BY `p`.`product_name`
ORDER BY RAND()
LIMIT 3
But this is returning an empty data set.
Try this:
SELECT pr.id, pr.name, pr.image, MIN(pi.price) min_price
FROM products pr INNER JOIN product_items pi
ON pr.product_id = pi.product_id
GROUP BY pr.id
精彩评论