簡體   English   中英

Postgres SQL中的`->>`和`->`有什么區別?

[英]What is the difference between `->>` and `->` in Postgres SQL?

SQL中的->>->有什么區別?

在這個線程中( 檢查字段是否存在於 json 類型列 postgresql 中),回答者基本上建議使用,

json->'attribute' is not null

代替,

json->>'attribute' is not null

為什么使用單箭頭而不是雙箭頭? 以我有限的經驗,兩者都做同樣的事情。

->返回 json(或 jsonb)並且->>返回text

with t (jo, ja) as (values
    ('{"a":"b"}'::jsonb,('[1,2]')::jsonb)
)
select
    pg_typeof(jo -> 'a'), pg_typeof(jo ->> 'a'),
    pg_typeof(ja -> 1), pg_typeof(ja ->> 1)
from t
;
 pg_typeof | pg_typeof | pg_typeof | pg_typeof 
-----------+-----------+-----------+-----------
 jsonb     | text      | jsonb     | text

PostgreSQL 提供了兩個原生運算符->->>來幫助您查詢 JSON 數據。

運算符->將 JSON 對象字段作為 JSON 返回。 運算符->>將 JSON 對象字段作為文本返回。

以下查詢使用運算符->以 JSON 形式獲取所有客戶:

SELECT
 info -> 'customer' AS customer
FROM
 orders;
customer
--------
"John Doe"
"Lily Bush"
"Josh William"
"Mary Clark"

以下查詢使用運算符->>以文本形式獲取所有客戶:

SELECT
 info ->> 'customer' AS customer
FROM
 orders;
customer
--------
John Doe
Lily Bush
Josh William
Mary Clark

您可以在下面的鏈接中查看更多詳細信息http://www.postgresqltutorial.com/postgresql-json/

Postgres 提供 2 個運算符來獲取 JSON 成員:

  • 箭頭運算符: ->返回 JSON 或 JSONB 類型
  • 雙箭頭運算符: ->>返回文本類型

我們還必須了解,我們現在有兩種不同的null

  • (null) postgres 空類型
  • null json/b 空類型

我在jsfiddle上創建了一個示例

讓我們創建一個帶有 JSONB 字段的簡單表:

create table json_test (
  id integer,
  val JSONB
);

並插入一些測試數據:

INSERT INTO json_test (id, val) values
(1, jsonb_build_object('member', null)),
(2, jsonb_build_object('member', 12)),
(3, null);

我們在 sqlfiddle 中看到的輸出:

id  | val
----+-----------------
 1  | {"member": null}
 2  | {"member": 12}
 3  | (null)

筆記:

  1. 包含一個 JSONB 對象並且唯一的字段membernull
  2. 包含一個 JSONB 對象,並且唯一的字段member具有數值12
  3. is (null) : 即整個列是(null)並且根本不包含 JSONB 對象

為了更好地理解差異,讓我們看一下類型和空檢查:

SELECT id,
  val -> 'member'  as arrow,
  pg_typeof(val -> 'member')  as arrow_pg_type,
  val -> 'member' IS NULL as arrow_is_null,
  val ->> 'member' as dbl_arrow,
  pg_typeof(val ->> 'member')  as dbl_arrow_pg_type,
  val ->> 'member' IS NULL as dbl_arrow_is_null,
  CASE WHEN jsonb_typeof(val -> 'member') = 'null' THEN true ELSE false END as is_json_null
from json_test;

輸出:

ID arrow_pg_type arrow_is_null dbl_arrow dbl_arrow_pg_type dbl_arrow_is_null is_json_null
1 無效的 jsonb 錯誤的 (無效的) 文本 真的 真的
2 12 jsonb 錯誤的 12 文本 錯誤的 錯誤的
3 (無效的) jsonb 真的 (無效的) 文本 真的 錯誤的

筆記:

  • 對於{"member": null}
    • val -> 'member' IS NULL
    • val ->> 'member' IS NULL為真
  • is_json_null可用於獲取 json- null條件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM