【问题标题】:how to group by a number of ids in a postgres array如何按postgres数组中的多个ID分组
【发布时间】:2015-11-05 17:35:47
【问题描述】:

我正在尝试根据 Postgres 数组(在 Postgres 9.4 中表示为文本字段)中的项目数来选择一行,并且能够在 Rails 4.2 中选择/分组

我有以下表格:

 queryable_id | liked_count | users_who_like_ids 
--------------+-------------+--------------------
         2376 |           3 | {1,80,78,101, 188}
        18771 |           1 | {78,101, 123,125}
         1790 |           1 | {78}
         2257 |           1 | {78}

比如我想说select and order by user_who_like_ids like

select * from items group by count(users_who_like_ids) where users_who_like_ids include (78,123,125)

我将如何进行此查询? Rails 是否支持这种类型的查询?

编辑 1

这里是 users_who_like_ids

 users_who_like_ids      | text[]                      | default '{}'::text[]

编辑 2

看起来有点像这样:

select queryable_id, liked_count, users_who_like_ids  from  queryables where users_who_like_ids  @> ARRAY['1','80'];

但这需要 1 和 80

【问题讨论】:

    标签: sql ruby-on-rails postgresql


    【解决方案1】:

    我想,你在找array_length()

    select
      *
    from 
      items
    where
      users_who_like_ids @> ARRAY[78,123,125]
    group by
      array_length(users_who_like_ids) 
    

    请注意,where 子句始终属于 group by 子句。

    【讨论】:

    • hmm... 听起来像这样的事情,但我在 include 语句中遇到错误。编辑问题...想知道是否应该是 ingeter[] - 第一次使用 postgres 数组
    • 啊,是的,我被误导了。您需要@> 运算符而不是includes。对不起,我会编辑我的答案。而且,是的,我预计数组是integer[]。如果您打算坚持使用text[],只需将您的数字用单引号括起来:ARRAY['78','123','125']
    猜你喜欢
    • 2020-11-11
    • 2015-11-18
    • 2018-08-22
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    相关资源
    最近更新 更多