为什么这个 PosgreSQL LIKE 查询不起作用?

Naf*_*ine 5 postgresql

PostgreSQL 9.2。

[local] postgres@host=# select * from units where ip_address LIKE '192.168.43.%';
ERROR:  42883: operator does not exist: inet ~~ unknown
 LINE 1: select * from units where ip_address LIKE '192.168.43.%';
                                              ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
LOCATION:  op_error, parse_oper.c:722
Time: 0.309 ms
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Abe*_*sto 12

错误信息清楚地描述了问题:“operator does not exist: inet ~~ unknown”

因此,您应该inettype使用本机运算符

在你的情况下应该是

... where ip_address << '192.168.43/24'::inet;
Run Code Online (Sandbox Code Playgroud)

其中斜杠后面的值指定值中的有效位数(24 位 = 3 个字节 = xyzany)。例如,192.168.128/17表示从192.168.128.0到 的任何地址192.168.255.255


您可以将一个inet值转换为varchar并像处理任何其他 varchar 一样处理它,但它会破坏原始类型的任何好处,并禁止索引(如果有)。但是,这是示例:

... where ip_address::varchar like '192.168.43.%/32';
Run Code Online (Sandbox Code Playgroud)

此外,如果ip_addressvalue 以上述方式部分限定,则它可能会提供错误的结果(例如,如果ip_address = '192.168/16'它不是这样的'192.168.1.%',这通常是错误的,因为 '192.168/16' 值包含从 '192.168.0.0' 到 '192.168.255.255' 的任何内容)