sql - IP 地址范围的 MS Access SQL 查询

标签 sql ms-access

IP 地址在联结表中以 192.168.0.1 - 192.168.0.254 格式存储在 Access 数据库中作为文本值。

连接表,例如区域

Name       IPAddress
Area1      192.168.0.1 - 192.168.0.254
Area2      192.168.1.1 - 192.168.1.254

我需要能够搜索这些范围之间的记录,例如

SELECT * FROM devices WHERE ipaddress = 192.168.0.1 /Returns record Name1

SELECT * FROM tablename WHERE ipaddress BETWEEN 192.168.0.1 AND 192.168.0.25 /Returns record Name1,Name2,Name3,etc

最佳答案

一个成功的方法由三部分组成:

  1. 解析 IPAddress 列并将其拆分为两个逻辑(文本)列:捕获范围的 IPAddressLowIPAddressHigh一个区域的IP。我们称其为 qryAreas:

    select
      [Name]
    , ... as IPAddressLow
    , ... as IPAddressHigh
    from Areas
    
  2. 实现一个函数(在 VBA 中,然后您可以从 Access SQL 中调用该函数)对 IP 地址进行比较。比较器函数可能是这样的:

    ' Returns:
    '  -1 if IP1 < IP2
    '   0 if IP1 = IP2
    '   1 if IP1 > IP2
    Function CompareIPAddresses(ip1 As String, ip2 As String) As Integer
      ip1_arr = Split(ip1, ".")
      ip2_arr = Split(ip2, ".")
    
      For i = 0 To 3
        ip1_arr(i) = CLng(ip1_arr(i))
        ip2_arr(i) = CLng(ip2_arr(i))
      Next i
    
      If ip1 = ip2 Then
        retval = 0
      ElseIf ip1_arr(0) < ip2_arr(0) Then
        retval = -1
      ElseIf ip1_arr(0) = ip2_arr(0) And ip1_arr(1) < ip2_arr(1) Then
        retval = -1
      ElseIf ip1_arr(0) = ip2_arr(0) And ip1_arr(1) = ip2_arr(1) And ip1_arr(2) < ip2_arr(2) Then
        retval = -1
      ElseIf ip1_arr(0) = ip2_arr(0) And ip1_arr(1) = ip2_arr(1) And ip1_arr(2) = ip2_arr(2) And ip1_arr(3) < ip2_arr(3) Then
        retval = -1
      Else
        retval = 1
      End If
    
      CompareIPAddresses = retval
    End Function
    
  3. 在查询中使用上述函数来确定 IP 地址是否等于某个值或在某个范围内。例如,如果您有一个地址 192.168.1.100 并且想知道它在哪个区域,您可以这样做:

    select [Name]
    from qryAreas
    where CompareIPAddresses(IPAddressLow, '192.168.1.100') in (-1, 0)
    and CompareIPAddresses('192.168.1.100', IPAddressHigh) in (-1, 0)
    

此处的 where 子句是更优雅的 where 192.168.1.100 between IPAddressLow and IPAddressHigh 语法的笨拙等效项,因为您没有 native IP 地址数据type 及其相应的运算符——所以你要自己动手。

关于sql - IP 地址范围的 MS Access SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23693884/

相关文章:

sql - 子查询返回多于一行

mysql - ER_WRONG_FIELD_WITH_GROUP : Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated

sql - 修剪 MS Access SQL 中的前导零

sql - 可以将今天的日期作为别名吗?

ms-access - 将 DAO 属性添加到数据库

C# Microsoft Access 参数化查询没有完成它的工作

mysql - 查找列值至少出现两次的行?

mysql - 使用 MySQL 多次选择同一列

SQL:通过多个表获取客户的总份额

c# - 如何从 MySQL 数据库内容动态创建 Access DB 并保存在本地