javascript - 如何避免在 postgres 数据库中插入空值

标签 javascript sql node.js postgresql pg-promise

我有以下查询将数据插入多对多连接表

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

但是我遇到的问题是用户不需要值 genre2Idgenre3Id 因此可以是 INTEGERNULL

我正在尝试找到一种方法来编写相同的查询,但它只在存在值时才插入。两列都有 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

关于javascript - 如何避免在 postgres 数据库中插入空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42579443/

相关文章:

javascript - Mongoose ObjectID 不能作为函数中的参数?

javascript - jssor slider ,如何设置自动播放时每张幻灯片的持续时间?

javascript - 找出有多少成千上万

SQL Server 2008 安装和服务帐户选项

javascript - 使用 Express.js 在服务器上发送 POST 请求

javascript - 如何使用 hygen 生成模板后运行脚本?

javascript - 单行 HTML CSS 上的长响应标题

JavaScript - 如何删除字符串中的某些空格

mysql - sql 计算所有记录属于具有多对多关系的父记录

php - 值为 NULL Codeigniter