我有一些表,它们都有一个名为created_at
的字段,这是一个时间戳,表示何时插入行
现在我使用mybatis 3作为持久层,当我用join
查询一些东西时,我发现它有点无聊。
看看我期望得到所有问题和答案的简单sql:
<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>
但是我发现,由于questions
和answers
都有字段created_at
,如果我写select q.*, a.*
,结果集中有2个created_at
,并且,第二个被忽略。因此,答案的created_at
值将为questions
,这是不正确的。
为了避免这种情况,我找到了两种方法,但都不好:
修改每个表的字段名,确保它们不相同。例如:
questions.created_at
->questions.q_created_at
,answers.created_at
->answers.a_created_at
。这是不好的,因为有很多这样的字段,如
id
,name
,title
,updated_at
,它使数据库难以读取和维护更改这些名称修改SQL。修改sql中的字段名,如:
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
这不是很好,因为我需要更改SQL中的每个字段名,它变得非常长,难以阅读,每次编写这样的SQL都很痛苦。
<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>
现在你的时间在atime
和qtime
中