2017-02-16 245 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

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