Array_agg alterantive - PostgreSQL

时间:2015-12-21 11:44:05

标签: sql postgresql

我正在使用postgreSQL版本8.3.4,它不支持该函数" array_agg"

我对这些表的定义是:

create table photos (id integer, user_id integer, primary key (id, user_id)); 

create table tags (photo_id integer, user_id integer, info text, primary key (user_id, photo_id, info));

我遇到了这个问题,它给了我我需要的东西:

    SELECT photo_id
   FROM   tags t
   GROUP  BY 1
   HAVING (SELECT count(*) >= 1
           FROM  (
              SELECT photo_id
              FROM   tags
              WHERE  info = ANY(array_agg(t.info))
              AND    photo_id <> t.photo_id
              GROUP  BY photo_id
              HAVING count(*) >= 1 
              ) t1
           )

但由于我的版本,我无法使用它。 我可以使用这个替代查询吗?

1 个答案:

答案 0 :(得分:0)

select 
  t2.photo_id, count(*) 
from tags t1 
join tags t2 on t1.info = t2.info and t1.photo_id <> t2.photo_id 
group by t2.photo_id
;

HAVING count = k如果你想要精确的k