我使用SQLITE3 PDO通过PHP连接到我的SpiceWorks数据库。我试图按IP地址顺序显示设备列表。这是我目前的查询:
SELECT name, ip_address FROM `devices` ORDER BY ip_address
这个问题是它组织起来像这样奇怪:
有没有简单的方法来解决这个问题?
我无法编辑数据库,因为它会通过SpiceWorks关闭。我需要一种在SQL中执行此操作的方法。
答案 0 :(得分:3)
您是否尝试过INET_ATON功能?这可能是一个迟到的答案,但也许它会帮助其他人。
SELECT name, ip_address
FROM devices
ORDER BY
INET_ATON(ip_address)
答案 1 :(得分:2)
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),
这样的事情应该有用。但这会很糟糕。 (这个应该按前两个八位字节排序......)
答案 2 :(得分:2)
我的实施方式如下:
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)
答案 3 :(得分:0)
由于我只关心最后一个八位位组,因此我能够使用非常简单的
SELECT name, ip_address FROM `devices`
ORDER BY CAST(substr(ip_address, 10) AS NUMERIC) DESC;
我的IP在最后一个八位字节之前有9个字符
答案 4 :(得分:-1)
您将字段设置为VARCHAR或其他字符字段,因此它将按第一个数字对它们进行排序。您需要按类型顺序将类型转换为数字。
像这样:
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 .....