简体   繁体   English

如何使用jooq连接3个表并迭代结果?

[英]How to join 3 tables and iterate results using jooq?

I have COURSE, STUDENT, SCHEDULE tables. 我有COURSE,STUDENT,SCHEDULE表。

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. 现在我想离开连接时间表与课程和学生表。

Question (1): 问题(1):

What's the best way to do join these 3 tables in jooq? 在jooq中加入这3个表的最佳方法是什么? 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();

Question (2): 问题2):

When I get the result, what's the best way to split results into Student objects and Course objects? 当我得到结果时,将结果拆分为Student对象和Course对象的最佳方法是什么? 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()....)
}

Answer 1 答案1

What's the best way to do join these 3 tables in jooq? 在jooq中加入这3个表的最佳方法是什么? I assume it's like [...] 我认为它就像[...]

While your query is correct , I wouldn't join like you did. 虽然你的查询是正确的 ,但我不会像你那样加入。 Your approach creates a derived table, which 您的方法创建了一个派生表

  1. Adds complexity to the SQL statement with no value, eg when maintaining the statement 在没有值的情况下为SQL语句添加复杂性,例如在维护语句时
  2. Prevents optimisation in some databases that poorly handle derived tables 在某些处理派生表的数据库中阻止优化

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();

Answer 2 答案2

You can use one of the various Record.into() methods, such as Record.into(Table) 您可以使用各种Record.into()方法之一,例如Record.into(Table)

for (Record r : result) {
    StudentRecord s = r.into(STUDENT);
    CourseRecord c = r.into(COURSE);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM