【问题标题】:Display detail data from mysql using group by使用 group by 显示来自 mysql 的详细数据
【发布时间】:2012-03-21 08:17:26
【问题描述】:

例如,我有一张桌子:

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

请帮忙!!

【问题讨论】:

标签: mysql


【解决方案1】:

请尝试以下查询

select * from products po
where price = 
(SELECT MIN(price) FROM products pi
where type = po.type)

如果你想添加一个时间组件(在你的 cmets 中写),查询应该是

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)

【讨论】:

    【解决方案2】:

    如果您先订购然后分组,您应该得到您想要的:

    SELECT type, price, name, id FROM products ORDER BY price DESC GROUP BY type;
    

    【讨论】:

    • 会显示最低价吗?
    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 2023-01-02
    • 1970-01-01
    • 2010-11-02
    相关资源
    最近更新 更多