繁体   English   中英

Mysql查询以选择PHP中第二高和第三高的值以及最后一个条目

[英]Mysql query to select the second and third highest value and last entry in PHP

我需要从最后一个条目中选择2和3最高值的代码。

SNO  Userid  Price

1    1004   10
2    1002   20
3    1001   300
4    1003   700
5    1002   80
6    1001   50

现在,我需要为1001、1002、1003、1004选择最后进入价格。

结果:

1001 - 50, 1002 - 80, 1003 -700, 1004 -10.

第二个最大值是80个用户1002第三个最大值是50个用户1001

select * from price order by price desc limit 2,1
union
select * from price order by price asc limit 1

据我了解,您想要第二,第三高和最小的最小值。

嗯,不确定我是否理解,但是请尝试以下操作:

SELECT t.*
FROM YourTable t
WHERE NOT EXISTS(SELECT 1 FROM YourTable s
                 WHERE t.userid = s.userid
                   AND s.sno > t.sno)
ORDER BY t.price DESC
LIMIT 2

您可以通过根据Userid的分组和SNO降序给SNO号来实现此目的。

询问

select t.`SNO`, t.`Userid`, t.`Price` from(
  select `SNO`, `Userid`, `Price`, (
    case Userid when @curA 
    then @curRow := @curRow + 1 
    else @curRow := 1 and @curA := `Userid` end 
  ) as `rn`
  from `your_table_name` t, 
  (select @curRow := 0, @curA := '') r 
  order by `Userid`, `SNO` desc
)t
where t.`rn` = 1; 

查询样例:

SELECT * FROM table ORDER BY Price LIMIT 2 OFFSET 1 DESC

如果我理解你的问题!

暂无
暂无

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

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