PostgreSQL使用array_agg检索包含数组中项目的记录

时间:2013-10-24 10:45:13

标签: arrays postgresql postgresql-8.4

我的数据库系统是PostgreSQL 8.4

以下是示例模式:

CREATE TABLE items(
  item_code varchar(20) NOT NULL PRIMARY KEY,
  item_description varchar(200),
  item_pieces_per_pack integer
);

CREATE TABLE customer_orders (
  order_id integer,
  item_code varchar(20),
  required_shipping_date date,
  quantity integer,
  PRIMARY KEY (order_id ,item_code,required_shipping_date)
);

INSERT INTO items VALUES ('AL0000063','PANETTONE CLASSICO BASSO 1KG',1);
INSERT INTO items VALUES ('AL0000064','PANDORO CLASSICO 1KG',1);
INSERT INTO items VALUES ('AL0000065','TORRONE CIOCCOLATO E NOCCIOLE 250G',4);
INSERT INTO items VALUES ('AL0000066','CANTUCCI TOSCANI 100G',6);
INSERT INTO items VALUES ('AL0000067','SAGRANTINO DI MONTEFALCO',6);
INSERT INTO items VALUES ('AL0000068','BAROLO',6);
INSERT INTO items VALUES ('AL0000069','AMARONE',6);


INSERT INTO customer_orders VALUES (1,'AL0000063','2013-12-15',5);
INSERT INTO customer_orders VALUES (1,'AL0000066','2013-12-15',15);
INSERT INTO customer_orders VALUES (1,'AL0000067','2013-12-14',15);
INSERT INTO customer_orders VALUES (2,'AL0000063','2013-12-11',25);
INSERT INTO customer_orders VALUES (2,'AL0000064','2013-12-11',25);
INSERT INTO customer_orders VALUES (2,'AL0000067','2013-12-13',25);
INSERT INTO customer_orders VALUES (3,'AL0000063','2013-12-13',25);
INSERT INTO customer_orders VALUES (3,'AL0000065','2013-12-10',10);
INSERT INTO customer_orders VALUES (3,'AL0000065','2013-12-20',10);

我需要从表中检索“items”,只记录数组中的item_code。 以下查询工作正常:

SELECT * FROM items
WHERE item_code = ANY('{AL0000063,AL0000064,AL0000065}'::text[])

但是当我使用带有array_agg的子查询时:

SELECT * FROM items
WHERE item_code = ANY(
  SELECT array_agg(DISTINCT item_code) 
  FROM customer_orders 
  WHERE required_shipping_date BETWEEN '2013-12-01' AND '2013-12-15')

PostgreSQL引发了错误:

错误:运算符不存在:字符变化=字符变化[]第2行:WHERE item_code = ANY(                         ^提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换。


为什么呢?

1 个答案:

答案 0 :(得分:2)

它必须是Postgres解析SQL的东西,因为额外强制转换为varchar []它可以正常工作:

 SELECT * FROM items
WHERE item_code = ANY((
  SELECT array_agg(DISTINCT item_code)
  FROM customer_orders
  WHERE required_shipping_date BETWEEN '2013-12-01' AND '2013-12-15')::varchar[]);

无论如何,在这种情况下不需要使用数组:

SELECT * FROM items
WHERE item_code IN (
  SELECT DISTINCT item_code
  FROM customer_orders
  WHERE required_shipping_date BETWEEN '2013-12-01' AND '2013-12-15');