【发布时间】:2011-11-09 13:28:30
【问题描述】:
我在一个包含几个数组列的 PostgreSQL 数据库中构建了一系列视图。视图定义如下:
create view articles_view as
(select articles.*,
array(select row(people.*)::people
from people
where articles.spubid=people.spubid and
people.stype='Author' and
bactive='t'
order by people.iorder) as authors,
array(select row(people.*)::people
from people
where articles.spubid=people.spubid and
people.stype='Editor' and
bactive='t'
order by people.iorder) as editors,
array(select row(people.*)::people
from people
where articles.spubid=people.spubid and
people.stype='Reviewer' and
bactive='t'
order by people.iorder) as reviewers,
array(select row(status.*)::status
from status
where articles.spubid=status.spubid and
bactive='t') as status
from articles
where articles.bactive='t');
基本上我想要做的是在“作者”列上添加一个 iLike,以确定该数组中是否存在特定的用户 ID。显然我不能在该数据类型上使用 iLike,所以我需要找到另一种方法。
以下是“作者”数组中的数据示例:
{"(2373,t,f,f,\"2011-08-01 11:57:40.696496\",/Pubs/pubs_edit_article.php,\"2011-08-09 15:36:29.281833\",000128343,A00592,作者,1,Nicholas,K.,Kreidberg,\"\",123456789,t,Admin,A,A,A,0,\"\")"," (2374,t,f,f,\"2011-08-01 11:57:40.706617\",/Pubs/pubs_edit_article.php,\"2011-08-09 15:36:29.285428\",000128343,A00592,作者,2,John,D.,Doe,\"\",234567890,t,IT,A,A,A,0,\"\")"," (2381,t,f,f,\"2011-08-09 14:45:14.870418\",000128343,\"2011-08-09 15:36:29.28854\",000128343,A00592,Author,3,Jane,E,Doe,\"\",345678901,t,Admin,A,A,A,,\"\")","(2383 ,t,f,f,\"2011-08-09 15:35:11.845283\",567890123,\"2011-08-09 15:36:29.291388\",000128343,A00592,作者,4,Test,T,Testerton,\"\",TestTesterton,f,N/A,A,A,A,,\"\")"}
我想要做的是查询视图并找出数组中是否存在字符串“123456789”(即分配给数组中的 Nicholas Kreidberg 的用户 ID)。我不在乎它被分配给哪个用户或它出现在数组中的什么位置,我只需要知道 '123456789' 是否出现在数组中的任何位置。
一旦我知道如何编写一个查询来确定上述条件是否为真,那么我的应用程序将简单地执行该查询,如果返回行,它将知道传递给查询的用户 ID 是该出版物的作者,并且相应地进行。
提前感谢您提供有关此主题的任何见解。
【问题讨论】:
-
有什么理由不能使用正确的数据库结构吗? IE。一个单独的作者表,如果它是 m:n 关系,则表将文章映射到作者。
-
@ThiefMaster 数组由 postgres 提供,问如何在一个数组中搜索是一个合理的问题。
-
@Dana,它仍然是一种反模式(没有规范化,没有索引可能,连接很痛苦,搜索很痛苦,而且速度非常慢)。
-
是的,数组对于某些事情来说很好,询问也很好。如果有人将它用于单独的表更有意义的情况(例如,通过 SQL 访问它而不是仅仅检索整个事物时)问他为什么不这样做就更好了。
-
@ThiefMaster:有一个作者表,其中的所有数据都被拉到数组列中的视图中。文章的流程是这样的:一个唯一的 pubid(以及大量其他数据)存储在文章表中。一个 pubid 可以有许多作者,这些作者存储在一个作者表中。一个 pubid 也可以有许多状态(因为它经历了发布的各个阶段),因此它可以在状态表中出现多次。该视图背后的想法是将所有数据(来自文章、作者和状态)集中到一个位置,以便更轻松/更快地查询并避免使用连接。
标签: sql database arrays postgresql