如何在 PostgreSQL 的数组中添加非重复项?

How to add non duplicate items inside an array in PostgreSQL?

 question_id | person_id |      question_title      |     question_source      | question_likes | question_dislikes |           created_at            
-------------+-----------+--------------------------+--------------------------+----------------+-------------------+---------------------------------
           2 | 2         | This is question Title 1 | This is question Video 1 |                |                   | 2021-11-11 10:32:53.93505+05:30
           3 | 3         | This is question Title 1 | This is question Video 1 |                |                   | 2021-11-11 10:32:58.69947+05:30
           1 | 1         | This is question Title 1 | This is question Video 1 | {2}            | {1}               | 2021-11-11 10:32:45.81733+05:30

我正在尝试在数组 question_likesquestion_dislikes 中添加值。我无法弄清楚使用 sql 在数组中仅添加非重复项的查询。我希望数组中的所有项目都是唯一的。

下面是我用来创建问题的查询 table:

CREATE TABLE questions(
    question_id BIGSERIAL PRIMARY KEY,
    person_id VARCHAR(50) REFERENCES person(person_id) NOT NULL,
    question_title VARCHAR(100) NOT NULL,
    question_source VARCHAR(100),
    question_likes TEXT[] UNIQUE,
    question_dislikes TEXT[] UNIQUE,
    created_at TIMESTAMPTZ DEFAULT NOW()
);
UPDATE questions 
  SET question_likes = array_append(question_likes,) 
WHERE question_id= 
RETURNING *

我可以对上述查询进行哪些更改以使其正常工作?

这是使用非规范化模型的缺点。仅仅因为 Postgres 支持数组,并不意味着它们是解决使用关系数据建模的最佳实践更好地解决的问题的好选择。

但是,在您的情况下,您可以通过在 WHERE 子句中添加一个附加条件来简单地防止这种情况发生:

UPDATE questions 
  SET question_likes = array_append(question_likes,) 
WHERE question_id= 
  AND  <> ALL(question_likes)
RETURNING *

如果在数组中的任何位置找到 的值,这将完全阻止更新。