如何获取postgres中的字段计数?

问题描述 投票:1回答:1

我有一个表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)

sql postgresql postgresql-9.3
1个回答
0
投票

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

select o.*, cardinality(string_to_array(product_id, ','))
from orders o
© www.soinside.com 2019 - 2024. All rights reserved.