代码之家  ›  专栏  ›  技术社区  ›  LPChip

MYSQL获取唯一ip的每个第一个id

  •  0
  • LPChip  · 技术社区  · 7 年前

    我有一个表,其中有一列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 回复  |  直到 7 年前
        1
  •  2
  •   M Khalid Junaid    7 年前

    进行自连接以获取第一个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

        2
  •  0
  •   Vineel Shah    7 年前

    这对我很有效:

    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引擎。你用的是什么发动机?其他人可能会有不同的反应。

        3
  •  0
  •   Mateusz    7 年前
    select `id`
    from (
        select * from `MyTable` order by `id` ASC
        ) x
    group by `ip`
    

    也许是这边?

        4
  •  0
  •   Firas Rassas    7 年前

    如果IPs表没有更多列,只需使用以下选项:

    select distinct(*) from `myTable`