簡體   English   中英

僅當名稱和位置不匹配時才插入

[英]INSERT INTO only if Name and Location DON'T match

如果它具有唯一的名稱和位置,我試圖只將一條記錄添加到我的 psql 表中。 如果表中不存在條目(名稱或位置),它可以插入記錄,但如果名稱已經存在,我的服務器會拋出錯誤以響應查詢。 到目前為止,這是我的代碼:

app.post("/addCampground", async (req, res) => {
    const name = req.body.name;

    const location = req.body.location;
    const leng = req.body.maxlength;
    const elev = req.body.elevation;
    const site = req.body.sites;
    const pad = req.body.pad;

try{
    
const template = "INSERT INTO campgrounds (name, location, maxlength, elevation,
 sites, padtype) VALUES ($1, $2, $3, $4, $5, $6) SELECT name, location WHERE NOT 
EXISTS(SELECT name, location from campgrounds where name =$1 AND location =$2) ";
console.log(template);
const response = await pool.query(template, [name, location, leng, elev, site,
 pad], [name, location]);

res.json({status: "added", results:{name:name, location:location} });
}catch (err){
    res.json({status: "campground already in database"});
}

})

有問題的查詢是:

const template = "INSERT INTO campgrounds (name, location, maxlength, elevation, sites, padtype) VALUES
 ($1, $2, $3, $4, $5, $6) SELECT name, location WHERE NOT EXISTS(SELECT name, location from campgrounds
 where name =$1 AND location =$2) ";

const response = await pool.query(template, [name, location, leng, elev, site, pad], [name, location]);

嘗試添加名稱匹配但位置不同的記錄時出現錯誤:

TypeError: cb is not a function
    at Query.callback (/home/sbeg/db-class-350/practice/task4/node_modules/pg-pool/index.js:376:18)
    at Query.handleError (/home/sbeg/db-class-350/practice/task4/node_modules/pg/lib/query.js:128:19)
    at Client._handleErrorMessage (/home/sbeg/db-class-350/practice/task4/node_modules/pg/lib/client.js:335:17)
    at Connection.emit (events.js:315:20)
    at /home/sbeg/db-class-350/practice/task4/node_modules/pg/lib/connection.js:115:12
    at Parser.parse (/home/sbeg/db-class-350/practice/task4/node_modules/pg-protocol/dist/parser.js:40:17)
    at Socket.<anonymous> (/home/sbeg/db-class-350/practice/task4/node_modules/pg-protocol/dist/index.js:10:42)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:295:12)
    at readableAddChunk (_stream_readable.js:271:9)

sql 的正確語法:

INSERT INTO campgrounds (name, location, maxlength, elevation, sites, padtype) 
SELECT ($1, $2, $3, $4, $5, $6)
WHERE NOT EXISTS(SELECT 1 from campgrounds where name =$1 AND location =$2)

或者,如果您在名稱、位置列上有唯一索引,則可以on confflict使用:

INSERT INTO campgrounds (name, location, maxlength, elevation, sites, padtype) 
VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT unique_index DO NOTHING

暫無
暫無

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

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