如何避免在Postgres数据库中插入空值
问题描述:
我有以下查询将数据插入到许多一对多连接表如何避免在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 *;
答
要只插入不空:
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
@GordonLinoff避免在我的表中加载'NULL'值和不必要的列。 – malimichael
直接相关:[用pg-promise跳过更新列](http://stackoverflow.com/questions/40697330/skip-update-columns-with-pg-promise)。 –
这很让人困惑,因为你接受一个答案,表明你试图插入的数据在另一个表中,而你自己的带有属性变量的例子指向使用内存中的数据。作为pg-promise的作者,我将发布一个正确的答案,但首先需要澄清那件事。 –