在一个 MySQL 命令中选择最大和最小记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4254567/
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 17:47:11  来源:igfitidea点击:

Selecting the Max and Min records in one MySQL command

mysql

提问by TheBounder

I need to be able select the two records from a table based on ID.

我需要能够根据 ID 从表中选择两条记录。

I need the first one, and the last one (so min, and max) IE.

我需要第一个和最后一个(最小和最大)IE。

table: Customer
    id    name
    1     Bob
    50    Bob

Any ideas? Thanks

有任何想法吗?谢谢

回答by SubniC

SELECT MIN(id), MAX(id) FROM tabla

EDIT:If you need to retrive the values of the row you can do this:

编辑:如果您需要检索行的值,您可以这样做:

SELECT *
FROM   TABLA AS a, (SELECT MIN(id) AS mini,
                            MAX(id) AS maxi
                     FROM   TABLA) AS m
WHERE  m.maxi = a.id
       OR m.mini = a.id;

回答by Albireo

Is this what you are looking for?

这是你想要的?

select id, name from customers where id = ( select max(id) from customers )
union all
select id, name from customers where id = ( select min(id) from customers )

Now I have tested this type of query on a MySQL database I have access, and it works. My query:

现在我已经在我可以访问的 MySQL 数据库上测试了这种类型的查询,并且它有效。我的查询:

SELECT nome, livello
FROM personaggi
WHERE livello = (
SELECT max( livello )
FROM personaggi ) 

回答by user2037142

If ties for first and/or last place are not a concern, then consider the following query:

如果第一个和/或最后一个位置的关系不是问题,请考虑以下查询:

(SELECT id, name FROM customers ORDER BY id DESC LIMIT 1)
UNION ALL
(SELECT id, name FROM customers ORDER BY id LIMIT 1);

回答by Shiwangini

It worked for me:

它对我有用:

    select * from customer where id in ((select min(id) from customer),(select max(id) 
from customer));

回答by Muhammed ?ahsuvaro?lu

SELECT MIN(value), MAX(value) FROM table

SELECT MIN(value), MAX(value) FROM 表