试图限制数量显示在mysql结果中

时间:2018-05-13 22:44:23

标签: mysql sql

我有一个存储id,项目,食物类型,图像和价格的表

我想将结果限制为商店中销售的每种类型之一,例如狗粮,猫粮,dvd降序 mysql数据库中保存的示例 表:Nunca

id      item                    type        image   price
=========================================================
1       Pedigree Pouches        dog food    img1    $4.99
2       Cesar Classic Selection dog food    img2    $3.99
3       Meaty Strips Chicken    dog food    img3    $2.99
4       Jelly Fish Selection    cat food    img4    $1.99
5       Bananas                 fruit       img5    $2.84
6       Celery                  vegetables  img6    $5.99
7       Apple                   fruit       img7    $0.95
8       Pineapple Juice         Soft drink  img8    $0.99
9       Oranges                 fruit       img9    $1.99
10      Cabbage                 vegetables  img10   $0.99
11      Suicide Squad           dvd         img11   $12.99

最终结果应该来自查询

id      item                    type        image   price
==========================================================
11      Suicide Squad           dvd         img11   $12.99
10      Cabbage                 vegetables  img10   $0.99
9       Oranges                 fruit       img9    $1.99
8       Pineapple Juice         Soft drink  img8    $0.99
4       Jelly Fish Selection    cat food    img4    $1.99
3       Meaty Strips Chicken    dog food    img3    $2.99

我尝试了各种mysql查询,但无济于事

2 个答案:

答案 0 :(得分:1)

典型方法使用相关子查询:

select n.*
from nunca n
where n.id = (select max(n2.id) from nunca n2 where n2.type = n.type);

这将选择每种类型的最后一行。

答案 1 :(得分:1)

select * from t where 
id in(select max(t.id) id from t group by t.type) 
order by id desc

我想可以有窗口或连接替代品,但这个似乎适合这个目的。