我正在使用MySQL,我正在尝试获取数据主键的前1000s值,如下所示:
+ --------- + ----------- + | id | name | + --------- + ----------- + | 1000 | George | | 1002 | David | | 2000 | Jane | | 2003 | Mary | | 3123 | Steven | | 3222 | Marta | | 10001 | Chris | | 10091 | Nathan | + --------- + ----------- +
And I'd like to grab the highest of the 1000s range. So my query would return something like this:
+ --------- + ----------- + | id | name | + --------- + ----------- + | 1002 | David | | 2003 | Mary | | 3222 | Marta | | 10091 | Nath | + --------- + ----------- +
This is what I have and it works:
SET @2k:= 2000;
SET @3k:= 3000;
SET @4k:= 4000;
SET @11k:= 11000;
SELECT sub1.id,
person.name
FROM
(SELECT max(id) id
FROM person
WHERE id < @2k
UNION
SELECT max(id) id
FROM person
WHERE id < @3k
UNION
SELECT max(id) id
FROM person
WHERE id < @4k
UNION
SELECT max(id) id
FROM person
WHERE id < @11k) sub1
JOIN person ON person.id = sub1.id
ORDER BY id ASC
这里是SQLFiddle:http://sqlfiddle.com/#!9/95ef8/14
同样,它可以工作,但是有没有一种更动态的方法,使我不必创建像@2k,@3k等变量,并创建联合?例如,如果表的id增加到数百万,那么上面的操作将涉及到太多的重构。
最佳答案
这将获得每组1000个中的最高密钥:
SELECT MAX(id) as max_per_thousand
FROM person
GROUP BY FLOOR(id/1000)
然后,您可以将其与person表连接以获取每个ID的整个记录:
SELECT p.*
FROM person AS p
JOIN (SELECT MAX(id) as maxid
FROM person
GROUP BY FLOOR(id/1000)) AS t
ON p.id = t.maxid
DEMO
关于mysql - 数千个范围组中的最高主键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25829821/