PostgreSQL的选择*,其中列包含数组值
问题描述:
我有一个PostgreSQL数据库这样的:PostgreSQL的选择*,其中列包含数组值
users
id name companyrestrictions
1 Bill [3, 4]
2 Fred [5, 6]
然后为每个公司3
变量在这种情况下
所以我写了这样的查询:
SELECT * FROM users WHERE 3 = ANY(users.companyrestrictions)
但我发现了以下错误: OP任何/所有(阵列)要求在右侧
公司限制数组类型的jsonb
我在做什么错?
答
尝试<@
包括operator:
<@ Are the left JSON path/value entries contained at the top level within the right JSON value?
SELECT * FROM users WHERE '3' <@ users.companyrestrictions
任何只适用于阵列
答
这可能是更好的存储公司限制另一个表。 这正是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;
由于错误提示:您不能在JSONB列上使用数组运算符。没有用于测试JSONB列内数组内的元素的等价函数。如果你想存储的只是一个数组,那你为什么不使用数组? –
我没有看到Postgres的数组数据类型,有没有一个?这叫什么? – Jordash
https://www.postgresql.org/docs/current/static/arrays.html –