我是sql的新手,我只是在数组尚未包含字符串的情况下尝试将字符串追加到文本数组列中:
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[]
);
即使我有一个范围= 2,id = 3,公司= 2且空数组的用户,此查询也不起作用。
它不工作,因为数组没有定义,或者我错过了什么?
PS:如果我删除AND NOT ('/test2/test3/aaaa' = ANY (sharedfolders))
它显然有效。
答案 0 :(得分:1)
sharedfolders
不能为null。使用空数组作为默认值
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, '{}'))