[英]Filter SQL rows that may be null
我正在嘗試在 Kotlin Exposed 中編寫一個將多個表連接在一起的查詢。 一些表可以有空值,在這種情況下, select
語句應該忽略那些。
舉個例子:我有一個UserTable
,一個GeoLocationTable
和一個PhotoTable
。 用戶將始終擁有一個引用的GeoLocation
表,但它可能有也可能沒有照片。 UserTable
對PhotoTable
,但PhotoTable
有一個userId
作為 FK。
我想實現這一點,當我查詢用戶時 - 我總是在結果集中收到一個用戶。 如果照片的外鍵為userId
,則照片應僅在結果集中,否則結果集中應僅包含用戶。
我的問題是,如果用戶的照片不在數據庫中,那么我的查詢甚至不會返回用戶! 我究竟做錯了什么?
這是查詢。
private fun fetchUserWithPhotos(userId: String) = tx {
val query = UserProfileTable
.join(
joinType = JoinType.LEFT,
otherTable = GeoLocationTable,
otherColumn = GeoLocationTable.id,
onColumn = UserProfileTable.geoLocationId
)
.join(
joinType = JoinType.LEFT,
otherTable = PhotoTable,
otherColumn = PhotoTable.userId,
onColumn = UserProfileTable.id
)
val x = query
.select {
(UserProfileTable.id eq userId) and
(UserProfileTable.deletedAt.isNull()) and
(UserProfileTable.enabled eq true) and
(PhotoTable.userPhotoType eq UserPhotoType.PROFILE.toString()) and
(PhotoTable.position eq 1)
}
// x is empty set here, even though the user EXISTS!
}
我怎樣才能總能得到用戶和照片?
我想我是直截了當的,我可以從您的代碼中解析的查詢結果如下:
select * from user_profile
left join geo_location on user_profile.geo_location_id = geo_location.id
left join photo on user_profile.id = photo.user_id
where user_profile.id = ?
and user_profile.deleted_at is null
and user_profile.enabled is true
and photo.user_photo_type = 'PROFILE'
and photo.position = 1;
您所描述的問題是:'如果用戶的照片不在數據庫中,那么我的查詢甚至不會返回用戶! 我究竟做錯了什么?'
問題:您使用的是基於照片表中數據的謂詞,您已經聲明用戶並不總是有照片條目。 如果沒有照片,則謂詞為假並且不會選擇該行,即使您知道用戶存在:
and photo.user_photo_type = 'PROFILE'
and photo.position = 1;
建議的解決方案:我認為您可以嘗試加入您想要的照片並僅維護用戶表上的謂詞。 將您的查詢更新為:
select * from user_profile
left join geo_location on user_profile.geo_location_id = geo_location.id
left join photo on user_profile.id = photo.user_id and photo.position = 1 and photo.user_photo_type = 'PROFILE'
where user_profile.id = ?
and user_profile.deleted_at is null
and user_profile.enabled is true;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.