将最受欢迎的值放入数组类型中

时间:2018-04-10 12:56:37

标签: sql postgresql

我有这样一张桌子:

               Table "public.items_tags_array"
 Column  |       Type        |           Modifiers           
---------+-------------------+-------------------------------
 item_id | character varying | not null
 tags    | text[]            | not null default '{}'::text[]
Foreign-key constraints:
    "items_tags_array_item_id_fkey" FOREIGN KEY (item_id) REFERENCES items(item_id)

tags字段包含数组格式的多个元素:

   item_id    |       tags       
--------------+------------------
 8eb6a7d9558c | {test,home,sun}
 3779a64d1bf9 | {test2,home,fam}

如何构建查询以获取最常用的标签(单个值)?

2 个答案:

答案 0 :(得分:2)

使用unnest():

select tag, count(tag)
from items_tags_array
cross join unnest(tags) as tag
group by 1
order by 2 desc

答案 1 :(得分:2)

使用unnest(anyarray)(参见documentation)从数组中获取元素集。然后按标签分组并获得最受欢迎。

SELECT
    tag,
    COUNT(*)
FROM (
    SELECT
        unnest(tags) AS tag
    FROM
        items_tags_array
    ) AS tag
GROUP BY
    tag
ORDER BY
    COUNT(*) DESC;