简体   繁体   English

MySQL语句以最大ID获得最小值

[英]MySQL statement to get min value with max ID

I want to select the minimum value with the largest id. 我想选择具有最大ID的最小值。 For example, I want to select Playstation because it has a larger id than Silly Puddy. 例如,我想选择Playstation,因为它的ID大于Silly Puddy。

This is my sql statement: 这是我的sql语句:

SELECT *, max(id), min(price)
FROM table
group by type
ORDER BY id DESC 


id      name                    type        price
123451  Park's Great Hits       Music       19.99
123452  Silly Puddy             Toy         3.99
123453  Playstation             Toy         3.99

I keep getting Silly Puddy returned for Toy. 我不断收到傻傻的布迪回去的玩具。 Any suggestions on what to do differently? 有什么建议可以做些不同的事情吗? Thanks in advance! 提前致谢!

as soon as id unique - there is only one price for one id, no any "minimum" or "maximum", just one: 一旦ID唯一-一个ID只有一个价格,没有任何“最小”或“最大”价格,只有一个:

select * from table where id in (
SELECT max(id)
FROM table as a
where a.price = (select min(price) from table as b where a.type=b.type)
group by type
) as t

Try this query. 试试这个查询。 This should do it. 这应该做。

select t4.* 

from 

`table` t4 

join 

( 

    select t2.type, max(t2.id) as id 
    from 
    `table` t2 join 
    (
        select type, min(price) as price
        from
        `table` t1
        group by type
    ) t3 on t2.type = t3.type and t2.price = t3.price
    group by t2.type

)  t5 on t4.id = t5.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM