简体   繁体   English

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

[英]How to get the count of the field in postgres?

I have a table orders whose structure is like this:我有一个表orders ,其结构如下:

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

I for the product_id I am inserting data like this:我对于 product_id 我正在插入这样的数据:

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

the product_id holds the different products that were ordered in a particular order. product_id包含以特定顺序订购的不同产品。 There is a entry in products table for each of the product_id .每个product_idproducts表中都有一个条目。

Now I want to get the counts of the product_id for a particular order.现在我想获取特定订单的product_id计数。

Example: For the above insertion I made, I should get something like:示例:对于我所做的上述插入,我应该得到如下内容:

Id    Count
1     2

How is it possible is postgresql? postgresql怎么可能?

Edit: Sorry for messing with the create table query.编辑:很抱歉弄乱了create table查询。 It's a varchar[] instead of varchar(255)这是一个 varchar[] 而不是 varchar(255)

You can convert the value to an array and measure the number of values:您可以将值转换为数组并测量值的数量:

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

DDL:下载:

CREATE TABLE tbl1 (id integer, count json);

INSERT INTO tbl1 (id, count) values (1, '["1", "2"]'::json), (2, '["3", "45"]');

Query:询问:

 SELECT id, sum(json_array_length(count)) as count from tbl1 group by id order by id;

Result:结果:

 id | count 

----+-------

  1 |     2

  2 |     2

I do hope it helps我希望它有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM