如何避免在Postgres数据库中插入空值

问题描述

要仅插入非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

解决方法

我有以下查询,将数据插入到多对多联接表中

INSERT INTO playlist_genre(playlist_id,genre_id)
VALUES  (${playlistId},${genre1Id}),(${playlistId},${genre2Id}),${genre3Id})
);

但是,我遇到的问题是用户并不需要这些值genre2Idgenre3Id,因此可以是anINTEGERNULL

我正在尝试找到一种方法来写入此相同的查询,但因此仅在存在值的情况下才插入。两列都有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 *;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...