PostgreSQL select *其中列包含数组值

时间:2017-11-11 15:38:40

标签: sql json postgresql jsonb

我有一个像这样的postgresql数据库:

users
id     name     companyrestrictions
1      Bill     [3, 4]
2      Fred     [5, 6]

然后是每个公司的变量3在这种情况下

所以我写了一个这样的查询:

SELECT * FROM users WHERE 3 = ANY(users.companyrestrictions)

但是我收到以下错误: op ANY / ALL(数组)需要右侧的数组

公司限制属于jsonb

类型

我做错了什么?

2 个答案:

答案 0 :(得分:3)

尝试<@包括operator

  

&lt; @ 左侧JSON路径/值条目是否包含在顶层   在正确的JSON值内?

SELECT * FROM users WHERE '3' <@ users.companyrestrictions

ANY仅适用于数组

答案 1 :(得分:1)

将公司限制存储在另一个表中可能更好。  这正是RDBMS的用途。

如果你真的需要使用JSON,你可能需要解析它。 postgres中可能有一些JSON函数可用,但它似乎是一个数组的麻烦,你将无法使用SQL查询数据。

CREATE TABLE t_user (
    id   SERIAL                 PRIMARY KEY NOT NULL,
    name CHARACTER VARYING(256) NOT NULL
);

CREATE UNIQUE INDEX t_user_idx ON t_users(name);

CREATE TABLE t_company (
    id   SERIAL                 PRIMARY KEY NOT NULL,
    name CHARACTER VARYING(256) NOT NULL
);

CREATE UNIQUE INDEX t_company_idx ON t_company(name);

CREATE TABLE t_company_restriction (
    id         SERIAL  PRIMARY KEY NOT NULL,
    id_company integer NOT NULL REFERENCES t_company(id) ON DELETE CASCADE,
    id_user    integer NOT NULL REFERENCES t_user(id) ON DELETE CASCADE
);

CREATE UNIQUE INDEX t_company_restriction_idx ON t_company_restriction(id_company, id_user);

INSERT INTO t_user(name) VALUES ('Bill');
INSERT INTO t_user(name) VALUES ('Fred');

INSERT INTO t_company (name) VALUES ('Company 1');
INSERT INTO t_company (name) VALUES ('Company 2');
INSERT INTO t_company (name) VALUES ('Company 3');
INSERT INTO t_company (name) VALUES ('Company 4');

INSERT INTO t_company_restriction (id_user, id_company)
SELECT u.id, c.id FROM t_user u, t_company c
WHERE u.name = 'Bill' AND c.name = 'Company 1';

INSERT INTO t_company_restriction (id_user, id_company)
SELECT u.id, c.id FROM t_user u, t_company c
WHERE u.name = 'Bill' AND c.name = 'Company 2';

INSERT INTO t_company_restriction (id_user, id_company)
SELECT u.id, c.id FROM t_user u, t_company c
WHERE u.name = 'Fred' AND c.name = 'Company 3';

INSERT INTO t_company_restriction (id_user, id_company)
SELECT u.id, c.id FROM t_user u, t_company c
WHERE u.name = 'Fred' AND c.name = 'Company 4';

SELECT u.name
FROM   t_user u, t_company c, t_company_restriction cr
WHERE  c.name = 'Company 1'
AND    c.id = cr.id_company
AND    u.id = cr.id_user;