【问题标题】:POSTGRESQL array does not contain valuePOSTGRESQL 数组不包含值
【发布时间】:2017-07-05 19:43:24
【问题描述】:

我是 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)),它显然可以工作。

【问题讨论】:

    标签: sql arrays database postgresql


    【解决方案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, '{}'))
    

    【讨论】:

    • 你以 1 秒的优势击败了我,刚刚做到了,它成功了,无论如何,谢谢。也将与 一起使用。你知道它在多行时是否表现良好?
    • select array_append(null::text[], '/test2/test3/aaaa') 给出一个数组?..
    • 啊 - 你的意思是它不能为空的 where 子句起作用
    • 这也不会使用数组索引。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 2019-03-28
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多