MySQL 在mysql查询中获取MAX值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11913408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:28:47  来源:igfitidea点击:

Get MAX value in mysql query

mysql

提问by thersa

I have a table

我有一张桌子

       id     mid    userid    remarks
       1       2       8          7 
       2       2       8          6
       3       2       8          4 
       4       2       8          5
       5       2       8          2
       6       2       8          3
       7       2       8          7
       8       2       8          0
       9       2       8          1
       10      2       8          8

I need the last row of remark before that row. i.e., remark '1'

我需要在该行之前的最后一行备注。即,备注“1”

SELECT MAX(id),mid,userid,remarks FROM sample 

回答by valex

Select Id,mid,userid,remarks from sample Where id<(select max(Id) from sample)
order by id desc limit 1

Or

或者

Select Id,mid,userid,remarks from sample 
order by id desc limit 1 offset 1

回答by Prince Jea

Try this:

尝试这个:

    SELECT MAX(id),mid,userid,remarks 
    FROM sample WHERE id NOT IN  (
    SELECT MAX(id) FROM sample
    )
    GROUP BY mid,userid,remarks 

EDIT

编辑

See if this works

看看这是否有效

SQL FIDDLE DEMO

SQL 小提琴演示

回答by WasiF

for mysql Node.jsdevelopers especially

尤其适用于mysql Node.js开发人员

I was unable to get direct-value in mysql-driver for node.js i.e. when I run the following query

我无法在 node.js 的 mysql-driver 中获得直接值,即当我运行以下查询时

SELECT MAX(id) FROM Users

and I got the result as [RowDataPacket { MAX(id): 1 }]

我得到的结果是 [RowDataPacket { MAX(id): 1 }]

I tried to retrieve the value from object console.log(MAX(id)), but I couldn't

我试图从 object 检索值console.log(MAX(id)),但我不能

so I set an aliasi.e. maxid

所以我设置了一个aliasiemaxid

SELECT MAX(id) as maxid FROM Users

and got it as [RowDataPacket { maxid: 1 }]

并得到它 [RowDataPacket { maxid: 1 }]

Which I can retrieve as console.log(maxid)

我可以检索为 console.log(maxid)