MySQL Select和LIMIT

时间:2012-04-18 12:29:53

标签: mysql select limit

我有一张桌子

id    ip
1     127.0.0.1
2     127.0.0.1
3     127.0.0.1
4     192.168.2.2
5     192.168.70.1
6     217.11.24.65

我需要从3 ips获取行,即如果我有限制3我必须得到 1,2,3,4,5

如果限制2 - 1,2,3,4

即。受到独特IP的限制

SELECT id FROM ips LIMIT 3 // returns 1,2,3 but i want 1,2,3,4,5

抱歉英语不好,谢谢理解。

1 个答案:

答案 0 :(得分:4)

SELECT id
FROM ips
WHERE ip IN (SELECT DISTINCT ip FROM ips ORDER BY id LIMIT 3)

由于MySQL 5.5尚未支持LIMIT内的ANY,这里有一个简单的解决方法:

SELECT id
FROM ips
WHERE ip IN (SELECT * FROM (SELECT DISTINCT ip FROM ips ORDER BY id LIMIT 3) alias)