簡體   English   中英

在數組中使用2個不同的參數在PostgreSQL中插入記錄

[英]Inserting records in PostgreSQL with 2 varying parameters from an array

我正在嘗試從數組中批量插入postgresql。 我當前正在做的是循環內的以下操作。

INSERT INTO table_name (
  first, second, third, forth
) VALUES (
  $1, $2, $3, $4
)

大約還有8到9個其他字段,並且每次迭代中只有2個字段發生變化。 我理想地想要做的是遵循此偽代碼的內容

FOREACH (obj IN $5)
  INSERT INTO table_name (
    first, second, third, forth
  ) VALUES (
    obj.fieldOne, $2, obj.fieldThree, $4
  ) 

並且僅提供$2$4 (不變的屬性),以及$5 ,這是一系列不斷變化的屬性,如下所示

[{one: 123, two: 63}]


我知道PostgreSQL允許在一個INSERT語句中插入多個值,但是構造查詢和管理其參數可能很麻煩,老實說,我由於參數和查詢字符串的麻煩而逃避它。

INSERT INTO tabel_name (
  first, second, third, forth
) VALUES (
  $1, $2, $3, $4
) VALUES (
  $5, $2, $6, $4
) VALUES (
  $7, $2, $8, $4
)

我還讀到Po​​stgreSQL具有像FOR和FOREACH這樣的循環,但是我不知道在這種情況下如何使用它們。 如果相關的話,我正在使用帶有pg-promise NodeJS。 任何幫助表示贊賞!

使用與多行插入相同的方法,您有兩個選擇:

  • 將其他固定的7個屬性添加到數組中的每個對象;

要么

  • 對僅在開頭設置的列使用預定義的值

第一個選項的解決方案很明顯,您只需遍歷數組並為7個屬性設置相同的值。

對於第二個選項,可以使用Column的屬性init將值重定向到靜態對象:

/* You can set this once, since you do not need to change it; */
const staticValues = {
  one: 111, three: 333, five: 555, six: 666, seven: 777, eight: 888, nine: 999
};

然后,您可以像這樣定義ColumnSet對象:

/* helper for defining our static-value column: */
const col = name => ({name, init: ()=> staticValues[name]});

/* Our ColumnSet object: */
const cs = new pgp.helpers.ColumnSet([
    col('one'),
    'two',
    col('three'),
    'four',
    col('five'),
    col('six'),
    col('seven'),
    col('eight'),
    col('nine')],
{table: 'table_name'});

現在,當您想生成一個完整的插入查詢時,可以將所有固定值設置到您的staticValues對象中,然后生成查詢:

const query = pgp.helpers.insert(data, cs);

這將基於您的原始想法生成查詢字符串,即您可以僅向其中的每個對象傳遞屬性為twofour屬性來傳遞data

然后,您可以執行查詢:

db.none(query).then().catch();

我的幾列取決於多個參數。 我該怎么做?

您可以以任何所需的方式定義此類列,因為Column類型非常靈活:

{
    name: 'col-name',
    init: c => pgp.as.format('myFunction(${one}, ${two}, ${three})', c.source),
    mod: ':raw'
}

或使用任何其他格式模板。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM