I have COURSE, STUDENT, SCHEDULE tables.
table course(id, name, ....),
table student(id, name, ...),
table schedule(id, c_id, s_id).
Now I want to left join schedule table with course and student table.
What's the best way to do join these 3 tables in jooq? I assume it's like:
TableLike<?> firstjoin = sql
.select()
.from(Tables.SCHEUDLE)
.leftOuterJoin(Tables.COURSE)
.on(Tables.SCHEDULE.CID.eq(Tables.COURSE.ID))
.asTable();
Result<?> result = sql
.select()
.from(firstjoin)
.leftOuterJoin(Tables.STUDENT)
.on(Tables.SCHEDULE.SID.eq(Tables.STUDENT.ID))
.fetch();
When I get the result, what's the best way to split results into Student objects and Course objects? I mean since the type is Result?, is there any way we can mapping result into student, course entities instead of tediously doing something like this:
for(Record r: result){
Student s = new Student(r.filed(), r.filed()...);
Course c = new Course(r.filed(), r.filed()....)
}
It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.
An SQL query can JOIN three tables (or more). Simply add an extra JOIN condition for the third table. 3-Table JOINs work with SELECT, UPDATE, and DELETE queries.
In a three-table join, Oracle joins two of the tables and joins the result with the third table. When the query in the following listing is executed, the EMP, DEPT, and ORDERS tables are joined together, as illustrated in Table 1.
In fact, you can join as many tables as you like – the idea behind it is the same as joining only two tables. It's very helpful to take a look at the data midstep and imagine that the tables you've already joined are one table.
What's the best way to do join these 3 tables in jooq? I assume it's like [...]
While your query is correct, I wouldn't join like you did. Your approach creates a derived table, which
Instead, just join both tables in a single statement:
Result<?> result = sql
.select()
.from(SCHEUDLE)
.leftOuterJoin(COURSE)
.on(SCHEDULE.CID.eq(COURSE.ID))
.leftOuterJoin(STUDENT)
.on(SCHEDULE.SID.eq(STUDENT.ID))
.fetch();
You can use one of the various Record.into()
methods, such as Record.into(Table)
for (Record r : result) {
StudentRecord s = r.into(STUDENT);
CourseRecord c = r.into(COURSE);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With