浏览嵌套 JSON
本课属于 Coddy PostgreSQL 学习旅程的“关联数据”单元。第 17 课,共 25 课。
-> 运算符会保留 JSON 值,因此你可以继续访问另一个对象。最后一步使用 ->> 提取 SQL 文本。如果中间键不存在,则会返回 NULL,而不会报错。
输入表 orders:
id | customer_id | amount | ordered_on | status | meta |
|---|---|---|---|---|---|
11 | 1 | 20 | 2025-01-02 | paid | {"channel":"web","items":2,"shipping":{"city":"Haifa"}} |
12 | 1 | 30 | 2025-01-04 | paid | {"channel":"app","items":3,"shipping":{"city":"Haifa"}} |
13 | 2 | 30 | 2025-02-01 | pending | {"channel":"web","items":1} |
14 | 3 | 50 | 2025-02-03 | paid | {"channel":"app","items":5,"shipping":{"city":"Eilat"}} |
15 | 2 | 10 | 2025-02-03 | paid | {"channel":"web","items":2} |
SELECT id, meta::jsonb -> 'shipping' ->> 'city' AS shipping_city FROM orders ORDER BY id;订单 11 从其 shipping 对象中返回 Haifa。订单 13 没有 shipping 对象,因此返回 NULL。如果过早将 shipping 转换为文本,就无法继续进行 JSON 导航。
将中间对象保留为 JSON,并使用 -> 提取最终文本。
挑战
中等返回 shipping.city 中的 id 和 destination。如果嵌套的 city 缺失,则使用 Pickup。按 id 排序。
输入表会显示在测试面板中。每次运行都会从全新的数据开始。按指定顺序返回命名列,不要对显示的行进行硬编码。
亲手试试
-- 在这里编写 SQL。
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
关联数据中的所有课
自己练习: PostgreSQL 在线编辑器