[英]How to store a list of IP addresses in SQL variable?
目标是查询多个 IP 地址。 我正在使用 HeidiSQL 运行此查询。
错误:
SQL 错误 (1064):您的 SQL 语法有错误;请检查与您的 MariaDB 服务器版本相对应的手册,以在第 1 行的“10.3.22.14”附近使用正确的语法。
SQL查询:
set @trunk='10.3.22.5','10.3.22.14';
set @sdate='2021-06-29 00:00:00', @edate='2021-06-29 23:59:00';
SELECT acctstarttime, acctstoptime, acctsessiontime, calledstationid, callingstationid, username, acctterminatecause, h323disconnectcause, h323calltype, acctstatustype, nasipaddress, nasportid, h323remoteaddress, acctinputoctets, servicetype, acctoutputoctets
FROM radius.radacct
where (acctstarttime between @sdate and @edate )
and nasipaddress in (@trunk);
如何修复此语法错误?
您不能将列表定义为变量。
set @trunk='10.3.22.5','10.3.22.14';
定义一个逗号分隔的列表,并使用FIND_IN_SET
。
set @trunk='10.3.22.5,10.3.22.14';
select FIND_IN_SET('10.3.22.5', @trunk);
首先,我真的不推荐你在做什么。 但是要获得正确的语法,您需要意识到'
在 SQL 中是一个特殊字符。 它是一个字符串分隔符。 所以:
set @trunk='10.3.22.5','10.3.22.14';
只是两个相邻的字符串。 MariaDB 无法识别该语法。 你想要做的是:
set @trunc = '10.3.22.5,10.3.22.14'
然后,您可以在查询中使用它而不是使用in
,而是使用find_in_set()
:
where find_in_set(nasipaddress, @trunc) > 0
请注意,使用函数find_in_set()
可防止使用索引。 因此,如果您的表很大,那么另一种解决方案是可取的,也许通过将值存储在表中并使用join
。
不能将列表定义为变量。
设置@trunk="10.3.22.5,10.3.22.14"; 选择 FIND_IN_SET("10.3.22.5", @trunk);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.