2017-02-16 242 views
0

我是新來的SQL和我試圖將字符串追加到文本陣列列僅如果陣列已經不包含字符串:PostgreSQL的數組不包含值

UPDATE users 
SET sharedfolders = array_append(sharedfolders, '/test2/test3/aaaa') 
WHERE companyid = 2 
AND scope = 2 
AND id = 3 
AND NOT ('/test2/test3/aaaa' = ANY (sharedfolders)) 

這裏是我的表:

CREATE TABLE users (
    id   SERIAL PRIMARY KEY, 
    companyid  INT REFERENCES companies (id) ON UPDATE CASCADE ON DELETE CASCADE, 
    email   VARCHAR UNIQUE, 
    lastname  VARCHAR(50), 
    firstname  VARCHAR(50), 
    password  VARCHAR, 
    scope   SMALLINT, 
    sharedfolders TEXT[] 
); 

即使我有一個scope = 2,id = 3,company = 2和一個空數組的用戶,該查詢也不起作用。

它不工作,因爲該數組沒有定義或我錯過了什麼?

PS:如果我刪除了AND NOT ('/test2/test3/aaaa' = ANY (sharedfolders))它顯然工作。

回答

1

sharedfolders對於它的工作不能爲空。使用空數組作爲默認值

create table users (
    id   int primary key, 
    companyid  int, 
    email   varchar unique, 
    lastname  varchar(50), 
    firstname  varchar(50), 
    password  varchar, 
    scope   smallint, 
    sharedfolders text[] default '{}' 
); 

而且<> all是清潔:

update users 
set sharedfolders = array_append(sharedfolders, '/test2/test3/aaaa') 
where companyid = 2 
and scope = 2 
and id = 3 
and '/test2/test3/aaaa' <> all (sharedfolders) 

如果有必要有null作爲默認然後比較前合併:

update users 
set sharedfolders = array_append(sharedfolders, '/test2/test3/aaaa') 
where companyid = 2 
and scope = 2 
and id = 3 
and '/test2/test3/aaaa' <> all (coalesce(sharedfolders, '{}')) 
+0

您打我1秒,只是做了它,它的工作原理,無論如何。也將與<>一起去。你知道它是否適合多行? – Gatsbill

+0

'select array_append(null :: text [],'/ test2/test3/aaaa')'給出一個數組嗎?.. –

+0

啊 - 你的意思是它不能爲空 –