【问题标题】:How to avoid inserting null values in postgres database如何避免在 postgres 数据库中插入空值
【发布时间】:2017-07-23 14:19:27
【问题描述】:

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

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 *;

【问题讨论】:

  • @GordonLinoff 以避免在我的表中加载大量 NULL 值和不必要的列。
  • 这令人困惑,因为您接受的答案表明您尝试插入的数据在另一个表中,而您自己的带有属性变量的示例指向使用内存中的数据。作为 pg-promise 的作者,我打算发布一个正确的答案,但你需要先澄清一下。
  • @vitaly-t 更新了我的问题以反映您的评论

标签: javascript sql node.js postgresql pg-promise


【解决方案1】:

只插入非空值:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 2022-08-15
    • 2019-03-27
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多