涉及整数[]的PostgreSQL查询
我有 2 个表:
CREATE TABLE article (
id serial NOT NULL,
title text,
tags integer[] -- array of tag id's from TAG table
)
CREATE TABLE tag (
id serial NOT NULL,
description character varying(250) NOT NULL
)
...并且需要根据文章标题从 ARTICLE 的“tags integer[]”中保存的 TAG 表中选择标签。
所以尝试了类似
SELECT *
FROM tag
WHERE tag.id IN ( (select article.tags::int4
from article
where article.title = 'some title' ) );
...这给了我
错误:无法将整数[]类型转换为整数
第 1 行:...FROM tag WHERE tag.id IN ((从...中选择article.tags::int4
我在开发和生产环境中都陷入了 PostgreSql 8.3 的困境。
I have 2 tables:
CREATE TABLE article (
id serial NOT NULL,
title text,
tags integer[] -- array of tag id's from TAG table
)
CREATE TABLE tag (
id serial NOT NULL,
description character varying(250) NOT NULL
)
... and need to select tags from TAG table held in ARTICLE's 'tags integer[]' based on article's title.
So tried something like
SELECT *
FROM tag
WHERE tag.id IN ( (select article.tags::int4
from article
where article.title = 'some title' ) );
... which gives me
ERROR: cannot cast type integer[] to integer
LINE 1: ...FROM tag WHERE tag.id IN ( (select article.tags::int4 from ...
I am Stuck with PostgreSql 8.3 in both dev and production environment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用数组重叠运算符
&&
:使用
contrib/intarray
,您甚至可以很好地索引此类内容。Use the array overlaps operator
&&
:Using
contrib/intarray
you can even index this sort of thing quite well.看一下“8.14.5. 在数组中搜索”,但请考虑该部分末尾的提示:
Take a look at section "8.14.5. Searching in Arrays", but consider the tip at the end of that section:
你没有提到你的 Postgres 版本,所以我假设你使用的是最新版本(8.4,9.0)
这应该可以工作:
但是你真的应该考虑改变你的表设计。
编辑
对于 8.3,可以轻松添加 unnest() 函数,请参阅此 wiki 页面:
http://wiki.postgresql.org/wiki/Array_Unnest
You did not mention your Postgres version, so I assume you are using an up-to-date version (8.4, 9.0)
This should work then:
But you should really consider changing your table design.
Edit
For 8.3 the unnest() function can easily be added, see this wiki page:
http://wiki.postgresql.org/wiki/Array_Unnest