在一个MySQL命令中选择Max和Min记录

时间:2010-11-23 09:35:32

标签: mysql

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

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

table: Customer
    id    name
    1     Bob
    50    Bob

有什么想法吗?感谢

5 个答案:

答案 0 :(得分:41)

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

编辑:如果您需要检索行的值,可以执行以下操作:

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;

HTH,问候。

答案 1 :(得分:3)

这是你在找什么?

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 )

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

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

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

对我有用:

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

答案 4 :(得分:-4)

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