Duplicate field names in different tables make the `SELECT` query complex in mybatis
I have some tables which all have a field named created_at
, that's a timestamp to represent when the row inserted.
Now I use mybatis 3 as the persistence layer, I found it a little boring when I query something with join
.
Look at the simple sql I expected to get all the questions and their answers:
<select id="selectQuestionsWithAnswers">
select q.*, a.* from questions as q left inner join answers as a
on q.id=a.id
order by a.created_at desc
</select>
But I found, since questions
and answers
both have field created_at
, and if I write select q.*, a.*
, there are 2 created_at
in the result set, and, the second one is ignored. So the answers will have the created_at
value as questions
, it's not correct.
To avoid this, I found 2 ways, but both not good:
Modify the field names of each table, make sure they are not same. For example:
questions.created_at
->questions.q_created_at
,answers.created_at
->answers.a_created_at
.This开发者_运维知识库 is not good because there are a lot of such fields as
id
,name
,title
,updated_at
, it makes the database hard to read and maintain to change these namesModify the SQL. Change the field names in sql, like:
select q.id as q_id, q.title as q_title, ..., q.created_at as q_created_at, a.id as a_id, a.content as a_content, ..., a.created_at as a_created_at from questions as q left inner join answers as a on q.id=a.id order by a.created_at desc
This is not good because I need to change every field names in the SQL, it becomes very long and hard to read, and painful to write such SQLs every time.
I'm new to mybatis, is there any better solution for this problem?
What about
<select id="selectQuestionsWithAnswers">
select q.*, a.*, q.created_at as qtime, a.created_at as atime from questions as q left inner join answers as a
on q.id=a.id
order by atime desc
</select>
now you'll have your times in atime
and qtime
精彩评论