1
我有以下查詢將數據插入到許多一對多連接表如何避免在Postgres數據庫中插入空值
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 *;
@GordonLinoff避免在我的表中加載'NULL'值和不必要的列。 – malimichael
直接相關:[用pg-promise跳過更新列](http://stackoverflow.com/questions/40697330/skip-update-columns-with-pg-promise)。 –
這很讓人困惑,因爲你接受一個答案,表明你試圖插入的數據在另一個表中,而你自己的帶有屬性變量的例子指向使用內存中的數據。作爲pg-promise的作者,我將發佈一個正確的答案,但首先需要澄清那件事。 –