PostgreSQL错误:列“ qty”的类型为整数,但表达式的类型为文本

时间:2019-09-01 23:42:38

标签: sql node.js postgresql casting

下面的查询是根据要插入的行数动态生成的。对于每一行数据,都有一个附加的UNION SELECT语句。

INSERT INTO account_sale
(qty, price, product_id)

SELECT $1, $2, t.id
  FROM inventory_product AS t
  WHERE  t.ebay_sku = $3

UNION

SELECT $4, $5, t.id
  FROM inventory_product AS t
  WHERE  t.ebay_sku = $6  
...

当我尝试运行查询时,得到以下信息:

  

错误:“ qty”列的类型为整数,但表达式的类型为文本

此查询的node.js页面:

module.exports = async function(orders) {
  const pool = require('./config.js');
  const client = await pool.connect();

  const sql = ...
  const data = [
    1, 1.50, 10, 
    2, 4.50, 11
  ];

  client.query(sql, data).then(res => {
  ...

  }).catch(err => console.log(err));
}

如果我从查询中删除UNION,如下所示:

INSERT INTO account_sale
(qty, price, product_id)

SELECT $1, $2, t.id
  FROM inventory_product AS t
  WHERE  t.ebay_sku = $3

并从data中删除第二项,没有任何错误。

我在这里想念什么?

1 个答案:

答案 0 :(得分:1)

要解决此错误,您需要 cast select语句中每一列的类型:

INSERT INTO account_sale
(qty, price, product_id)

SELECT $1::integer, $2::float, t.id
  FROM inventory_product AS t
  WHERE  t.ebay_sku = $3

UNION

SELECT $4::integer, $5::float, t.id
  FROM inventory_product AS t
  WHERE  t.ebay_sku = $6  
...

我能找到的解释这件事的壁橱是在this问题中@DenisdeBernardy的评论中:

  

这是由于Postgres强制键入的方式。通过一次选择,它将基于语句的插入部分来推断类型,而对于联合,则将基于联合的第一行推断类型,并由于缺乏提示而回退为文本。