sql - 将 int、float 和 boolean 存储在同一数据库列中

标签 sql json postgresql jsonb

是否有一种合理的方法可以将 int、float 和 boolean 值存储在 Postgres 的同一列中?
如果有类似的东西:

<表类=“s-表”> <标题> 摆脱 时间 值 <正文> 2d9c5bdc-dfc5-4ce5-888f-59d06b5065d0 2021-01-01 00:00:10.000000 +00:00 true 039264ad-af42-43a0-806b-294c878827fe 2020-01-03 10:00:00.000000 +00:00 2 b3b1f808-d3c3-4b6a-8fe6-c9f5af61d517 2021-01-01 00:00:10.000000 +00:00 43.2

目前我使用 jsonb 来存储它,但现在的问题是,我无法使用例如更大的运算符在表中进行过滤。

查询

SELECT * 
FROM points 
WHERE value > 0;

返回错误:

ERROR: operator does not exist: jsonb > integer: No operator matches the given name and argument types. You might need to add explicit type casts.

对我来说,在 true 的情况下,可以将 bool 值处理为 1 或 0或false 。是否有可能使用 jsonb 实现这一目标,或者是否有另一种 super 类型可以让我使用能够使用所有三种类型的列?

性能在这里并不是太重要,因为我在该表中的记录很少,我猜最多 5k。

最佳答案

如果您只是存储整数和 float ,通常您会使用 floatnumeric专栏。

但是有一个令人讨厌的true

您可以转换 JSON...

select *
from test
where value::float > 1;

...但是有一个令人讨厌的true

您必须将 bool 值转换为数字才能使其工作。

select *
from test
where
  (case when value = 'true' then 1.0 when value = 'false' then 0.0 else value::float end) >= 1;

或者忽略它。

必须围绕类型系统进行工作,这表明 value 实际上是两个甚至三个不同的字段塞进一个字段中。考虑将它们分成多列。

关于sql - 将 int、float 和 boolean 存储在同一数据库列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73912243/

相关文章:

mysql - 无法在 MariaDB 中执行 REPLACE

sql - 如何优化sql查询?好像distinct很慢?

javascript - AngularJS - 无法在 View 中访问检索到的 JSON 数据

php - 编码 php postgres json_encode

mysql - 返回相对于过去 7 天的 "most commented"列表的单个 SQL 查询,但该列表始终必须包含某些内容

json - 从内部具有用户对象的 json 解析用户(使用 Codable)

javascript - 检索 json 中唯一键的所有值

ruby-on-rails - Heroku 迁移 : type modifier is not allowed for type "bytea"

arrays - 如何将两个数组的交集结果转换​​为整数数组从SQL查询到postgresql中的整数数组

asp.net - 选择单选按钮后如何对 GridView 进行排序