我使用 SQLITE3 PDO 通过 PHP 连接到我的 SpiceWorks 数据库。我正在尝试按 IP 地址顺序显示设备列表。这是我当前的查询:
SELECT name, ip_address FROM `devices` ORDER BY ip_address
这样做的问题是它像这样奇怪地组织它们:
有什么简单的方法可以解决这个问题吗?
我无法编辑数据库,因为它会通过 SpiceWorks 关闭。我需要一种在 SQL 中执行此操作的方法。
我使用 SQLITE3 PDO 通过 PHP 连接到我的 SpiceWorks 数据库。我正在尝试按 IP 地址顺序显示设备列表。这是我当前的查询:
SELECT name, ip_address FROM `devices` ORDER BY ip_address
这样做的问题是它像这样奇怪地组织它们:
有什么简单的方法可以解决这个问题吗?
我无法编辑数据库,因为它会通过 SpiceWorks 关闭。我需要一种在 SQL 中执行此操作的方法。
您是否尝试过 INET_ATON 功能?这可能是一个迟到的答案,但也许它会帮助其他人。
SELECT name, ip_address
FROM devices
ORDER BY
INET_ATON(ip_address)
我已经实现了这样的:
SELECT IP FROM iplist ORDER BY
CAST(substr(trim(IP),1,instr(trim(IP),'.')-1) AS INTEGER),
CAST(substr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)) ,1, instr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)),'.')-1) AS INTEGER),
CAST(substr(substr(trim(IP),length(substr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)) ,1, instr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)),'.')))+length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)) ,1, instr(substr(trim(IP),length(substr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)) ,1, instr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)),'.')))+length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)),'.')-1) AS INTEGER),
CAST(substr(trim(IP),length(substr(substr(trim(IP),length(substr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)) ,1, instr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)),'.')))+length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)) ,1, instr(substr(trim(IP),length(substr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)) ,1, instr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)),'.')))+length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)),'.')))+ length(substr(trim(IP),1,instr(trim(IP),'.')))+length(substr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)) ,1, instr(substr(trim(IP),length(substr(trim(IP),1,instr(trim(IP),'.')))+1,length(IP)),'.')))+1,length(trim(IP))) AS INTEGER)
ORDER BY
CAST(substr(ip_address,1,instr(ip_address,'.')) AS NUMERIC),
CAST(substr(ip_address,instr(ip_address,'.'), instr(substr(ip_address,instr(ip_address,'.')))) AS NUMERIC),
像这样的东西应该工作。不过会很恶心。(这应该按前两个八位字节排序......)
因为我只关心最后一个八位字节,所以我能够使用非常简单的
SELECT name, ip_address FROM `devices`
ORDER BY CAST(substr(ip_address, 10) AS NUMERIC) DESC;
我的 ip 在最后一个八位字节之前有 9 个字符
您将字段作为 VARCHAR 或其他字符字段,因此它按第一个数字对它们进行排序。您需要将类型转换为 order by 语句中的数字。
像这样:
SELECT name, ip_address
FROM devices
ORDER BY
CAST(PARSENAME([ip_address], 4) AS INT),
CAST(PARSENAME([ip_address], 3) AS INT),
CAST(PARSENAME([ip_address], 2) AS INT),
CAST(PARSENAME([ip_address], 1) AS INT)
只是不确定这是否适用于 SQLlite .....