英文:
golang/pq : "pq: function uniq(integer[]) does not exist"
问题
这是我的代码(在gin中正常工作):
query :=`
UPDATE posts SET liked_by = array_append(liked_by, $1)
WHERE id = $2
RETURNING liked_by`
return p.DB.Exec(query, userID, post.ID)
我得到的错误信息是:
pq: function uniq(integer[]) does not exist
我的代码在没有使用uniq()
函数时可以正常工作。但是数组中会包含重复的值。我想确保我的数组只包含唯一的值。
英文:
Here's my code (works fine with gin)
query :=`
UPDATE posts SET liked_by = uniq(array_append(liked_by, $1))
WHERE id = $2
RETURNING liked_by`
return p.DB.Exec(query, userID, post.ID)
The error I'm getting
pq: function uniq(integer[]) does not exist
My code works fine without uniq()
. But the array is taking duplicate values. I wanna make sure my array only contains unique values.
答案1
得分: 1
问题出在你的SQL语句上(不是Go或lib/pq
),你可以通过运行以下SQL语句来复现这个问题:
select uniq('1,2,3,4'::integer[])
参考这个问题中的讨论,其中一个最简单的解决方案可能是:
select array_agg(distinct x) from unnest(array_append('1,2,3,4'::integer[], 4)) t(x)
将这个集成到你的代码中,大致如下(未经测试!):
query :=`
UPDATE posts SET
liked_by = (select array_agg(distinct x) from unnest(array_append(liked_by, $1)) t(x))
WHERE id = $2
RETURNING liked_by
`
英文:
The issue is with your SQL (not Go or lib/pq
); you can replicate the problem by running the following SQL:
select uniq('{1,2,3,4}'::integer[])
See this this question for a discussion of potential solutions, one of the simplest is probably:
select array_agg(distinct x) from unnest(array_append('{1,2,3,4}'::integer[], 4)) t(x)
Integrating this into your code gives something like (untested!):
query :=`
UPDATE posts SET
liked_by = (select array_agg(distinct x) from unnest(array_append(liked_by, $1)) t(x))
WHERE id = $2
RETURNING liked_by
`
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论