Java 筛选可能为空的SQL行

Java 筛选可能为空的SQL行,java,kotlin,kotlin-exposed,Java,Kotlin,Kotlin Exposed,我试图在Kotlin Exposed中编写一个将多个表连接在一起的查询。有些表可以有空值,在这种情况下,select语句应该忽略这些值 举个例子:我有一个UserTable、一个GeoLocationTable和一个PhotoTable。用户将始终拥有一个参考的地理位置表,但它可能有照片,也可能没有照片。UserTable不知道有关PhotoTable的任何信息,但是PhotoTable有一个作为FK的userId 我想实现这一点,当我查询用户时,我总是在结果集中收到一个用户。只有当存在将use

我试图在Kotlin Exposed中编写一个将多个表连接在一起的查询。有些表可以有空值,在这种情况下,
select
语句应该忽略这些值

举个例子:我有一个
UserTable
、一个
GeoLocationTable
和一个
PhotoTable
。用户将始终拥有一个参考的
地理位置
表,但它可能有照片,也可能没有照片。
UserTable
不知道有关
PhotoTable
的任何信息,但是
PhotoTable
有一个作为FK的
userId

我想实现这一点,当我查询用户时,我总是在结果集中收到一个用户。只有当存在将
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;
您所描述的问题是:“如果用户的照片不在数据库中,那么我的查询甚至不会返回用户!我做错了什么?”

问题:您正在使用基于照片表中数据的谓词,您已经声明用户并不总是有照片条目。如果没有照片,则谓词为false,即使您知道用户存在,也不会选择该行:

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;

使用
如果[row]不是空的
@Spectric您能更具体一点吗?您的示例中的
行是什么?将
[row]
替换为您希望确保有值的行。@Spectric您希望我将该代码确切地放在哪里?你介意写一个更详细的例子吗?