例如,我有一张桌子:
id name type price
123451 Park's Great Hits Music 19.99
123452 Silly Puddy Toy 3.99
123453 Playstation Toy 89.95
123454 Men's T-Shirt Clothing 32.50
123455 Blouse Clothing 34.97
123456 Electronica 2002 Music 3.99
123457 Country Tunes Music 21.55
123458 Watermelon Food 8.73
如果我想按类型选择最便宜的价格,我会用这个:
<?php
// Make a MySQL Connection
$query = "SELECT type, MIN(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "The cheapest ". $row['type']. " is $" .$row['MIN(price)'];
echo "<br />";
}
?>
然后,它将显示:
The cheapest Clothing is $32.50
The cheapest Food is $8.73
The cheapest Music is $3.99
The cheapest Toy is $3.99
但是,我想知道最便宜商品的详细信息,以便显示:
The cheapest Clothing is $32.50 which is Men's T-Shirt and id is 123454
The cheapest Food is $8.73 which is Watermelon and id is 123458
The cheapest Music is $3.99 which is Electronica 2002 and id is 123452
The cheapest Toy is $3.99 which is SillyPuddy and id is 123452
请帮助!!
答案 0 :(得分:2)
请尝试以下查询
select * from products po
where price =
(SELECT MIN(price) FROM products pi
where type = po.type)
如果要添加时间组件(在评论中为wirtten),则查询应为
select id, name, type, price, time from products po
where price =
(SELECT MIN(price) FROM products pi1
where type = po.type)
and time =
(SELECT MIN(time) FROM products pi2
where type = po.type
and price = po.price)
答案 1 :(得分:0)
如果您先订购然后分组,您应该得到您想要的东西:
SELECT type, price, name, id FROM products ORDER BY price DESC GROUP BY type;