简体   繁体   English

Postgresql - 在嵌套查询中使用 json function 的问题 - hstore

[英]Postgresql - problem using json function in nested queries - hstore

I have a table orders with a field order_detail of type hstore which saves json data.我有一个带有 hstore 类型字段 order_detail 的表订单,它保存 json 数据。

Now I want to query on the inner objects of my json data.现在我想查询我的 json 数据的内部对象。 because The query is somehow complicated I'm trying to tell my problem in easier scenario.因为查询有点复杂我试图在更简单的情况下告诉我的问题。

I have tested these 4 subqueries:我已经测试了这 4 个子查询:

  1. Get the original saved json:获取原始保存的json:

     select order_detail::json as original from orders;

    This query successfully returns the json formatted data.此查询成功返回 json 格式的数据。

  2. Get the inner object 'transaction' inside the order_details:在 order_details 中获取内部 object 'transaction':

     select order_detail::json as original, (order_detail -> 'transaction')::json as transaction from order_details;

    This query also works successfully.此查询也可以成功运行。

  3. Get the id of that transaction:获取该交易的 id:

     select order_detail::json as original, (order_detail -> 'transaction')::json as transaction, ((order_detail -> 'transaction')::json -> 'id')::text as id from order_details;

    The above also works successfully and returns the original json, transaction and id inside the transaction.以上也成功运行并返回原始json,事务和事务内的id。

  4. Select based on the result of query 3 and get one of the results: Select 根据查询 3 的结果得到结果之一:

     select original from (select order_detail::json as original, (order_detail -> 'transaction')::json as transaction, ((order_detail -> 'transaction')::json -> 'id')::text as id from order_details) s where transaction is null and id is null;

    This query will raise an exception: The exception says that:此查询将引发异常:异常表示:

    [22P02] ERROR there is a token '=' is invalid** [22P02] 错误有一个令牌 '=' 无效**

    Why does this exception occurs only in the 4th query?为什么这个异常只发生在第4 个查询中? Can anyone help me on this?谁可以帮我这个事?

Finally I found the problem.最后我发现了问题。 When you want have such a field which is json stored in hstore, if you use a simple query you can use something like this:当您想要在 hstore 中存储 json 这样的字段时,如果您使用简单的查询,您可以使用以下内容:

order_detail -> 'trasaction'

and this will return the transaction part of hashed-stored data in the order_detail field with no problem.这将毫无问题地返回 order_detail 字段中散列存储数据的事务部分。

BUT if you want to use such thing in a nested query, you MUST explicitly declare that the field is json.但是如果你想在嵌套查询中使用这样的东西,你必须明确声明该字段是 json。 so you must use something like this instead (in all parts of inner query):所以你必须使用这样的东西(在内部查询的所有部分):

order_detail::json -> 'transaction'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM