![](/img/trans.png)
[英]How to update only one column and avoid NULL values for others in node-postgres?
[英]How to avoid inserting null values in postgres database
我有以下查詢,將數據插入到多對多聯接表中
INSERT INTO playlist_genre(playlist_id, genre_id)
VALUES (${playlistId}, ${genre1Id}),
(${playlistId}, ${genre2Id}),
(${playlistId}, ${genre3Id})
);
但是我遇到的問題是用戶不需要genre2Id
和genre3Id
值,因此可以是INTEGER
或NULL
。
我正在嘗試找到一種方法來寫入此相同的查詢,但因此僅在存在值時才插入。 兩列都具有NOT NULL
約束。
編輯 :
這是我的播放列表課程
class Playlist {
constructor(playlist) {
// required fields
this.title = playlist.title;
this.playlistType = playlist.playlistType;
this.userId = playlist.userId;
this.numberOfTracks = playlist.numberOfTracks;
this.lengthInSeconds = playlist.lengthInSeconds;
this.genre1Id = playlist.genre1Id;
// not required fields
this.genre2Id = playlist.genre2Id || null;
this.genre3Id = playlist.genre3Id || null;
this.description = playlist.description || null;
this.releaseDate = playlist.releaseDate || null;
}
save() {
return new Promise((resolve, reject) => {
db.one(sqlCreatePlaylist, this)
.then((insertedPlaylist) => {
// Here is where i want to use insertedPlaylist's id
// to insert data into 'playlist_genre' table
resolve(insertedPlaylist);
})
.catch(error => reject(error));
});
}
這是sqlCreatePlaylist的樣子
INSERT INTO playlists(
user_id,
title,
playlist_type,
number_of_tracks,
duration,
description,
release_date
)
VALUES(
${userId},
${title},
${playlistType},
${numberOfTracks},
${lengthInSeconds},
${description},
${releaseDate}
)
RETURNING *;
要僅插入非null:
insert into playlist_genre (playlist_id, genre_id)
select playlist_id, genre_id
from (values
(${playlistid}, ${genre1id}),
(${playlistid}, ${genre2id}),
(${playlistid}, ${genre3id})
) s (playlist_id, genre_id)
where genre_id is not null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.