0

我的数据库系统是 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( ^ 提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换。


为什么?

4

1 回答 1

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');
于 2013-10-24T13:01:10.973 回答