回答

收藏

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

技术问答 技术问答 233 人阅读 | 0 人回复 | 2023-09-12

我有以下查询,将数据插入到多对多联接表中
! p# z, j1 i4 f$ JINSERT INTO playlist_genre(playlist_id, genre_id)+ Z: m, b# R3 E' e6 p
VALUES  (${playlistId}, ${genre1Id}),
# K; |* B" p5 p$ ?3 D        (${playlistId}, ${genre2Id}),, Z: q& l8 \% D1 }& w: m' J/ G4 e
        (${playlistId}, ${genre3Id})
' ~1 W0 `  x- b& D4 R' x2 N  z);
( n' C( [2 \7 S但是,我遇到的问题是用户并不需要这些值genre2Id和genre3Id,因此可以是anINTEGER或NULL。+ N$ \/ \8 {% I, g1 c
我正在尝试找到一种方法来写入此相同的查询,但因此仅在存在值的情况下才插入。两列都有NOT NULL约束。( Y2 _8 I$ t9 b: T
编辑" n2 V# R2 r0 ?* t
这是我的播放列表课程
1 z9 Y, R9 ^) `* Y* P  K% e. o5 kclass Playlist {
3 L, e7 w: d0 H! r3 x& y  constructor(playlist) {
3 p3 C: c5 l" H- g    // required fields+ y3 y" Z9 Q9 h! v. T9 _8 z
    this.title = playlist.title;
1 t8 @, g+ `* |( n4 F    this.playlistType = playlist.playlistType;# r' r6 h8 ^( F* w2 V0 Y9 @% O9 n
    this.userId = playlist.userId;
0 J: `; H& }! q1 s  L3 V2 q! }    this.numberOfTracks = playlist.numberOfTracks;7 d7 g* W/ X* I+ g2 i
    this.lengthInSeconds = playlist.lengthInSeconds;4 V4 O' ^' u/ s6 _4 P3 ~8 R8 Y
    this.genre1Id = playlist.genre1Id;4 x  J8 G8 D% A( V
    // not required fields
; M" o, p9 ^1 F) q    this.genre2Id = playlist.genre2Id || null;
+ l5 c3 }% L0 q0 b    this.genre3Id = playlist.genre3Id || null;  h: H+ E; U5 j
    this.description = playlist.description || null;" D6 @) X1 s+ B, x, v; j
    this.releaseDate = playlist.releaseDate || null;
$ H+ X7 E8 g5 s) d8 N  }
- y, ?1 k/ A% Y- H. }8 N  save() {
& Y1 B& z) s  @9 H! Z    return new Promise((resolve, reject) => {
+ o9 W, T( s1 z      db.one(sqlCreatePlaylist, this)# x( j0 Y( P* c( ?3 U, V$ \0 r
        .then((insertedPlaylist) => {3 K! t$ Z( g0 u# m) P
          // Here is where i want to use insertedPlaylist's id   x7 C: o0 j% I7 E4 k
          // to insert data into 'playlist_genre' table9 y4 ^5 ?; m# b$ C2 v0 D" P
          resolve(insertedPlaylist);* |# P9 G( T# q4 j, X' v8 v7 ]
        })% g! h6 v, k" N2 b/ P
        .catch(error => reject(error));( X, B8 w9 K* f. `/ a6 _* m
    });3 u& v/ N. q7 Q- a* m8 f3 Q
  }
" d. A+ r! K* `! b这是sqlCreatePlaylist的样子
1 p' q% t6 h: i' uINSERT INTO playlists(9 l. f+ r4 m8 C7 a
  user_id,
  A. a" U# m& R. J: i0 V1 Q: [. s  title,' b7 i- c/ q! c
  playlist_type,
; h* Z+ \* \  x. v6 W, o: D  number_of_tracks,
) X+ G" B" e$ o, D4 F  duration,& s2 Y" J& m$ L! E" P4 |
  description,
0 T$ w5 A. j+ s+ k# O: O+ A( f0 K  release_date7 ]  Z! r4 V! y  z* q
)
' p; [7 ~! n" F! v# RVALUES(
$ `  A) x% C6 E  I  U  ${userId},
& u1 v, T# K9 @# n  M* G# z) g' w  ${title},; }' N, `# f/ L; [' x* U  E* q8 K
  ${playlistType},
" L/ |& |7 _2 Y, o7 h  [  ${numberOfTracks},' M1 A; ~7 Z9 X
  ${lengthInSeconds},
$ |& `6 z( M8 `! R( I" I  ${description},
+ l3 E3 A( q  ~0 a: [: k+ c0 E  ${releaseDate}
: o5 c2 I! l6 T6 T)
. S6 B) C6 O" V: l8 B1 SRETURNING *;
# g& J$ r" B8 N9 I3 [               
+ r- `/ R" }9 \* ~, G解决方案:
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则