首页 > 解决方案 > 如何获取postgres中的字段计数?

问题描述

我有一张表orders,其结构如下:

create table orders (id serial primary key, created_at timestamp, updated_at timestamp, product_id varchar[]);

我对于 product_id 我正在插入这样的数据:

insert into orders values (1,now(),now(),'{"1","2"}');

product_id保存以特定顺序订购的不同产品。products表中的每个条目都有一个条目product_id

现在我想获取product_id特定订单的计数。

示例:对于我所做的上述插入,我应该得到如下内容:

Id    Count
1     2

postgresql怎么可能?

编辑:很抱歉弄乱了create table查询。这是一个 varchar[] 而不是 varchar(255)

标签: sqlpostgresqlpostgresql-9.3

解决方案


您可以将值转换为数组并测量值的数量:

select o.*, cardinality(product_id)
from orders o

推荐阅读