将子查询(根据排序选择记录)转换为JOIN

时间:2013-01-18 00:41:35

标签: mysql sql join

我有这个问题:

SELECT *
  FROM iptable
 WHERE ip = (SELECT ip
               FROM iptable
              WHERE name = 'username'
              ORDER BY date DESC
              LIMIT 0,1
            )
   AND name != 'username'

以下是它的作用:

  • 用户输入名称(在这种情况下,用户名
  • 查询从 iptable (仅限IP)
  • 获取最新记录
  • 使用返回的IP搜索 iptable 其他用户

查询运行良好,但我想知道是否可以使用JOIN而不是子查询?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您正在从给定用户的最新IP中选择进入ip的所有名称。 (我最初误读了查询,所以这有帮助。)

以下内容将此转换为显式联接:

select ip.*
from iptable ip join
     (select date, max(ip) as maxip
      from iptable
      where name = 'username'
      group by date
      order by date desc
      limit 1
     ) ips
     on ips.maxip = ip.ip
where is.name <>  'username'

(可能有一些假设,名称和ips永远不会为NULL。)

我确实想指出,原始版本仍在进行连接,而不是明确。

挑战在于获取最新的IP名称。这是另一种方法,它使用group_concatsubstring_index

select ip.*
from iptable ip join
     (select name,
             substring_index(group_concat(ip order by date desc), ',', 1) as lastip
      from iptable
      where name = 'username'
      group by name
     ) ips
     on ips.lastip = ip.ip
where ips.name <> ip.name
相关问题