[英]Postgres jsonb and query
I have a postgres database. 我有一个postgres数据库。 Inside "match" table I store a JSONB like this one, inside "when" column:
在“匹配”表中,我在“时间”列中存储了这样的JSONB:
{{"end": "2017-01-04T17:22:13.311693Z", "start": "2017-01-04T16:22:13.311693Z"}, {"end": "2017-01-04T17:22:13.311693Z", "start": "2017-01-04T16:22:13.311693Z"}}
and it works like a list of object storing a start time and an end time. 它的工作方式类似于存储开始时间和结束时间的对象列表。 Now i want to query all matches that are not past.
现在,我想查询所有未过去的匹配项。 How can i do that?
我怎样才能做到这一点? Is it possible to compare a single "start" value with the current data?
是否可以将单个“起始”值与当前数据进行比较?
Have a look at this SQL Fiddle . 看看这个SQL Fiddle 。
You can query into the jsonb using the ->>
operator. 您可以使用
->>
运算符查询jsonb。 For dates/times, you'll need to convert the results in order to compare. 对于日期/时间,您需要转换结果以便进行比较。 This query returns only values with a future start:
此查询仅返回将来开始的值:
SELECT when_col->>'start' FROM match
WHERE to_date(when_col->>'start','YYYY-MM-DD"T"HH24:MI:SS') >= NOW();
Note that the JSON you gave above was malformed. 请注意,您在上面提供的JSON格式错误。 I broke it out into separate rows in the fiddle:
我在小提琴中将它分成几行:
CREATE TABLE match
(
when_col jsonb
);
INSERT INTO match (when_col) VALUES ('{"end": "2017-01-04T17:22:13.311693Z", "start": "2017-01-04T16:22:13.311693Z"}');
INSERT INTO match (when_col) VALUES ('{"end": "2017-02-04T17:22:13.311693Z", "start": "2017-02-04T16:22:13.311693Z"}');
INSERT INTO match (when_col) VALUES ('{"end": "2019-02-04T17:22:13.311693Z", "start": "2019-02-04T16:22:13.311693Z"}');
INSERT INTO match (when_col) VALUES ('{"end": "2029-02-04T17:22:13.311693Z", "start": "2029-02-04T16:22:13.311693Z"}');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.