I have two tables: product and prices.
Products sample dataCode:CREATE TABLE `products` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , `productname` VARCHAR( 255 ) NOT NULL ) TYPE = MYISAM ; CREATE TABLE `prices` ( `fk_productid` INT UNSIGNED NOT NULL , `retailer` VARCHAR( 255 ) NOT NULL , `price` INT UNSIGNED NOT NULL ) TYPE = MYISAM ;
1 Test product
2 Sample product
Prices sample data
1 mystore 1000
1 otherstore 1020
1 thestore 1241
2 astore 451
2 newstore 331
2 mystore 553
2 thestore 112
Now I would like to get all products and the two or three prices with the lowest price for each product. And this preferable with only one query. I don’t want to have another query in a loop at least. Since I will run this in a php-script with a lot of products and a lot of prices.
In my humble mind I thought that this would work but no! It returns two prices for product id 2 and nothing else.
Result:PHP Code:SELECT *
FROM products p1
INNER JOIN (
SELECT *
FROM prices
ORDER BY price ASC
LIMIT 2
) p2
ON p1.id = p2.fk_productid
Do I need to create a stored procedure or something?Code:id productname fk_productid retailer price 2 Sample product 2 thestore 112 2 Sample product 2 newstore 331
All help are appreciated!!
Here is the full dbstructure with sample data:
Code:CREATE TABLE `prices` ( `fk_productid` int(10) unsigned NOT NULL, `retailer` varchar(255) NOT NULL, `price` int(10) unsigned NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; INSERT INTO `prices` VALUES (1, 'mystore', 1000); INSERT INTO `prices` VALUES (1, 'otherstore', 1020); INSERT INTO `prices` VALUES (1, 'thestore', 1241); INSERT INTO `prices` VALUES (2, 'astore', 451); INSERT INTO `prices` VALUES (2, 'newstore', 331); INSERT INTO `prices` VALUES (2, 'mystore', 553); INSERT INTO `prices` VALUES (2, 'thestore', 112); CREATE TABLE `products` ( `id` int(10) unsigned NOT NULL auto_increment, `productname` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; INSERT INTO `products` VALUES (1, 'Test product'); INSERT INTO `products` VALUES (2, 'Sample product');Edit:
Using MySQL 5.0.13, i can upgrade if it would help










Bookmarks