Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql:按或条件选择行-包括遍历json数组_Sql_Arrays_Json_Postgresql_Where Clause - Fatal编程技术网

Postgresql:按或条件选择行-包括遍历json数组

Postgresql:按或条件选择行-包括遍历json数组,sql,arrays,json,postgresql,where-clause,Sql,Arrays,Json,Postgresql,Where Clause,我通过以下查询创建了一个表: create table data ( id integer not null unique, owner text, users jsonb not null ); 该表如下所示: +----+-------+---------------------------------------------+ | id | owner | users | +----+--

我通过以下查询创建了一个表:

create table data
(
    id integer not null unique,
    owner text,
    users jsonb not null
);
该表如下所示:

+----+-------+---------------------------------------------+
| id | owner |                    users                    |
+----+-------+---------------------------------------------+
|  1 | alice | []                                          |
|  2 | bob   | [{"accountId": "alice", "role": "manager"}] |
|  3 | john  | [{"accounId": "bob", "role": "guest"}]      |
+----+-------+---------------------------------------------+
我需要代表Alice获取第1行和第2行

获取基于所有者的行非常有效:

SELECT *
FROM data
WHERE owner = 'alice'
尽管可以管理,但获取基于jsonb的行有点棘手:

SELECT *
FROM data, jsonb_array_elements(users) x
WHERE (x ->> 'accountId') = 'alice'
但是把它们放在一起让我得到的只是基于jsonb的:

SELECT *
FROM data, jsonb_array_elements(users) x
WHERE owner = 'alice' OR (x ->> 'accountId') = 'alice'
如何获得如下所示的选择

+----+-------+---------------------------------------------+
| id | owner |                    users                    |
+----+-------+---------------------------------------------+
|  1 | alice | []                                          |
|  2 | bob   | [{"accountId": "alice", "role": "manager"}] |
+----+-------+---------------------------------------------+
如果我能得到这样的选择就更好了

+----+----------+
| id |   role   |
+----+----------+
|  1 | owner    |
|  2 | manager  |
+----+----------+

问题在于空json数组,当与jsonb_数组_元素交叉连接时,它会从结果集中逐出相应的行。相反,可以进行左侧连接:

请注意,如果数组始终包含0或1个元素,则您不需要横向联接-您的查询将更简单:

select d.*
from data d
where 'alice' in (d.owner, d.data -> 0 ->> 'accountId')
-两个查询都返回:

id | owner | users -: | :---- | :------------------------------------------ 1 | alice | [] 2 | bob | [{"role": "manager", "accountId": "alice"}] id | owner | users -: | :---- | :------------------------------------------ 1 | alice | [] 2 | bob | [{"role": "manager", "accountId": "alice"}]