MYSQL获取独特ip的每个第一个id

时间:2017-11-18 21:19:36

标签: php mysql greatest-n-per-group

我有一个表,其中包含一个带有id'的列和一个带有ip地址的列。表中还有其他信息,但对于这个问题,我只关注ip地址。

我需要弄清楚表中每次出现的第一个ip地址,并返回id号。

有许多类似的问题,但它们都是较老的问题,而且他们的答案似乎不会因某种原因而起作用。

这是一个示例表:

+----+-----------------+
| id | ip              |
+----+-----------------+
|   1| 123.45.67.89    |
|   2| 123.45.67.89    |
|   3|  98.76.54.32    |
|   4| 123.45.67.89    |
|   5|  98.76.54.32    |
|   6|  11.22.33.44    |
+----+-----------------+

我想要回来的结果是(如果需要,它可能有ip列):

+----+
| id |
+----+
|   1|
|   3|
|   6|
+----+

但要么我得到所有结果,要么我得到最后一个ID:4,5,6

我尝试了什么:

SELECT DISTINCT(`ip`), `id` 
FROM `MyTable`
ORDER BY `id` ASC
-- this gives all rows.

SELECT `id`
FROM `MyTable`
GROUP BY `ip`
ORDER BY `id` ASC
-- this works but seems to completely ignore the ORDER BY statement, I get the last id, instead of first.

SELECT `ip` FROM
(   SELECT `ip`
    FROM `MyTable`
    ORDER BY `id` ASC
) as rows
GROUP BY `ip`
-- the id is not specified here and as such not returned. 

SELECT `ip`, `id` FROM
(   SELECT `ip`, `id`
    FROM `MyTable`
    ORDER BY `id` ASC
) as rows
GROUP BY ip
-- finds the uniques, but again does not sort, so instead returns the last occurence, not the first.

我怎样才能让它在2017年开始运作?

4 个答案:

答案 0 :(得分:2)

自我加入以获得第一次出现的ip

select a.*
from demo a
left join demo b on a.ip = b.ip
and a.id > b.id
where b.id is null

demo

答案 1 :(得分:0)

select `id`
from (
    select * from `MyTable` order by `id` ASC
    ) x
group by `ip`

也许这样?

答案 2 :(得分:0)

如果您的IP表没有更多列,请使用:

select distinct(*) from `myTable`

答案 3 :(得分:0)

这对我有用:

select id from MyTable group by ip order by id

如果您在订购时遇到问题,请尝试以下操作:

select id from 
(SELECT id
FROM MyTable
GROUP BY ip) tmpTable order by id

如果这不起作用,那么您的表定义就会出现问题。尝试发布您的create语句和任何索引创建语句。

另外,我的表正在使用InnoDB引擎。你用的是什么引擎?其他人可能会有不同的反应。