SQL连接:从重复项中选择最后的记录

时间:2018-03-31 11:51:07

标签: mysql sql

我正在研究python项目" Linux Server Monitor"。加载监控网站时,您创建的服务器和表格如下所示:

服务器:

+-----------+-----------+---------+-------------+
| server_id | auth_code | user_id | server_name |
+-----------+-----------+---------+-------------+
|         0 | xyz123    |       1 | My Server 1 |
|         1 | aabb      |      45 | BlaBlaUser  |
|         2 | asdfh1    |       1 | My Server 5 |
+-----------+-----------+---------+-------------+

创建服务器后,启动python脚本,它开始将监控数据上传到此表(所有用户都存储了所有数据):

监控数据:

+----+-----------+---------+---------+------------+-----------------+------------------+
| id | auth_code | user_id | os_name | os_version |   external_ip   | some_other_table |
+----+-----------+---------+---------+------------+-----------------+------------------+
|  0 | aabb      |      45 | Ubuntu  |      16.04 |    77.88.99.100 | dynamic data     |
|  1 | aabb      |      45 | Ubuntu  |      16.04 |    77.88.99.100 | dynamic data 2   |
|  2 | aabb      |      45 | Ubuntu  |      16.04 |     10.10.10.10 | dynamic data 3   |
|  3 | xyz123    |       1 | Fedora  |         27 |     92.94.95.99 | different data 1 |
|  4 | xyz123    |       1 | Fedora  |         27 |     92.94.95.99 | different data 2 |
|  5 | xyz123    |       1 | Fedora  |         27 |     92.94.95.99 | different data 3 |***
|  6 | asdfh1    |       1 | CentOS  |          7 |         5.5.5.5 |  some new data 1 |
|  7 | asdfh1    |       1 | CentOS  |          7 |         5.5.5.5 |  some new data 2 |
|  8 | asdfh1    |       1 | CentOS  |          7 |         2.2.2.2 |  some new data 3 |###
+----+-----------+---------+---------+------------+-----------------+------------------+

我想加入第一个和第二个表格以显示用户" important"这样的信息:

您的活动服务器:

+-----------+-------------+---------+------------+-----------------+
| server_id | server_name | os_name | os_version |   external_ip   |
+-----------+-------------+---------+------------+-----------------+
|         0 | My Server 1 | Fedora  |         27 |     92.94.95.99 |***
|         2 | My Server 5 | CentOS  |          7 |         2.2.2.2 |###
+-----------+-------------+---------+------------+-----------------+

如果我通过user_id加入第一个和第二个表,它也将加载重复项,但我只想要该特定用户服务器的最后插入记录。在这种情况下,在最后一条记录" external_ip"一台服务器已更改但其他服务器保持不变(标有***和###)。

1 个答案:

答案 0 :(得分:1)

您可以在subselect上使用内部联接作为用户的最大ID,监视器上的服务器

  select s.server_id, s.server_name, m.os_name, m.os_version, m.external_ip
  from servers s
  inner join Monitoring  m  on m.user_id = s.user_id  and s.auth_code = m.auth_code
  inner  join (
    select max(id) max_id,  user_id, os_name, os_version
    from Monitoring
    group by  user_id, os_name, os_version
  ) t  on t.max_id =  m.id
  where user_id = 1