2017-11-11 153 views
0

我有一個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

我在做什麼錯?

+0

由於錯誤提示:您不能在JSONB列上使用數組運算符。沒有用於測試JSONB列內數組內的元素的等價函數。如果你想存儲的只是一個數組,那你爲什麼不使用數組? –

+0

我沒有看到Postgres的數組數據類型,有沒有一個?這叫什麼? – Jordash

+0

https://www.postgresql.org/docs/current/static/arrays.html –

回答

3

嘗試<@包括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 

任何只適用於陣列

+0

返回這個錯誤:'操作符不存在:integer <@ jsonb' – Jordash

+0

奇怪 - ''3''不是整數.. –

+0

你是對的,我沒有注意到你把3變成了一個字符串,它現在可以工作,即使你有這樣一個數組''[3,33,333]''這樣的數組嗎? – Jordash

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;