将唯一值更新到Postgres数组

时间:2018-11-16 09:19:14

标签: spring postgresql hibernate spring-data-jpa

我遇到的情况是更新Postgres类型的bigint[]表列。每当触发update查询时,该数组内部应具有唯一的数字。

查询如下所示

UPDATE book_shelf 
SET book_id = book_id || array[CAST(:bookID AS BIGINT)], updated_at = now() 
WHERE user_id = :userID AND shelf_name = :shelfName

当上面的查询被触发时,它只是将数字添加到我不想发生的数组中。它应仅包含唯一值。请帮助我。

1 个答案:

答案 0 :(得分:0)

您可以在添加数组之前检查它是否存在:

UPDATE book_shelf 
SET book_id = CASE WHEN CAST(:bookID AS BIGINT) = ANY(book_id) THEN book_id ELSE ARRAY_APPEND(book_id, CAST(:bookID AS BIGINT)) END, updated_at = now() 
WHERE user_id = :userID AND shelf_name = :shelfName

当然,如果updated_at仅在book_id实际更新时才应设置,则将检查放在WHERE子句中,这样就不会不必要地更新它:

UPDATE book_shelf 
SET book_id = ARRAY_APPEND(book_id, CAST(:bookID AS BIGINT)), updated_at = now() 
WHERE user_id = :userID
AND shelf_name = :shelfName
AND NOT CAST(:bookID AS BIGINT) = ANY(book_id)