子查询
有类型子查询
基于单列的IN表达式
- Java
- Kotlin
BookTable book = Tables.BOOK_TABLE;
AuthorTableEx author = TableExes.AUTHOR_TABLE_EX;
List<Book> books = sqlClient
.createQuery(book)
.where(
book.id().in(sqlClient
.createSubQuery(author)
.where(author.firstName().eq("Alex"))
.select(author.books().id())
)
)
.select(book)
.execute();
val books = sqlClient
.createQuery(Book::class) {
where(
table.id valueIn subQuery(Author::class) {
where(table.firstName eq "Alex")
select(table.books.id)
}
)
select(table)
}
.execute()
最终生成的SQL如下
select
tb_1_.ID,
tb_1_.NAME,
tb_1_.EDITION,
tb_1_.PRICE,
tb_1_.STORE_ID
from BOOK as tb_1_
where
tb_1_.ID in (
select
tb_3_.BOOK_ID
from AUTHOR as tb_2_
inner join BOOK_AUTHOR_MAPPING as tb_3_
on tb_2_.ID = tb_3_.AUTHOR_ID
where
tb_2_.FIRST_NAME = ?
)
基于多列的IN表达式
- Java
- Kotlin
BookTable book = Tables.BOOK_TABLE;
List<Book> newestBooks = sqlClient
.createQuery(book)
.where(
Expression.tuple(
book.name(),
book.edition()
).in(sqlClient
.createSubQuery(book)
.groupBy(book.name())
.select(
book.name(),
book.edition().max()
)
)
)
.select(book)
.execute();
val newestBooks = sqlClient
.createQuery(Book::class) {
where(
tuple(
table.name,
table.edition
) valueIn subQuery(Book::class) {
groupBy(table.name)
select(
table.name,
max(table.edition).asNonNull()
)
}
)
select(table)
}
.execute()