如何在postgresql版本12中实现LIKE条件


Select COUNT(*) from Table_one where timestamp LIKE '%2020-03-04%' AND speed_type = 'SPEED';

当我通过spring-boot框架实现它时,这个查询显示错误,所以我在postgresql上检查了它,但它仍然显示错误。

错误是:-

ERROR:  operator does not exist: date ~~ unknown
LINE 1: Select COUNT(*) from table_one where timestamp LIKE '2020-0...
^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.
SQL state: 42883
Character: 49

使用日期/时间函数!不要转换为字符串!

where timestamp >= '2020-03-04' AND
timestamp < '2020-03-05' AND
speed_type = 'SPEED'

这不仅可以防止不必要的类型转换。但它也不受任何可能影响字符串转换的国际化设置的影响(这可能取决于数据库(。

它还可以使用包括timestamp的适当索引。优化器有更好的信息,可以改进查询计划(尽管在这种情况下,计划确实很简单(。

您需要将timestamp列强制转换为VARCHAR,以便将其与字符串进行比较:

Select COUNT(*) 
from Table_one 
where CAST(timestamp AS VARCHAR) LIKE '%2020-03-04%'
AND speed_type = 'SPEED';

dbfiddle 演示

因为您将时间戳值与字符串类型值进行比较。因此,需要像这样的转换

timestamp::text LIKE '%2020-03-04%'

最新更新