我有两个表,其中(roll_no)在两个表中都相同。 我有一个表(学生)有列名和roll_no。 e.g
roll_no name
----------------
123 John
它与另一个表(student_changed)有关系。其中包含列名,roll_no和LastEditTime。 e.g。
roll_no name LastEditTime
--------------------------------------
123 Johny 2017-11-09 06:00:00
123 John 2017-11-08 07:00:00
我想问的是,如何让联接拥有最新的 LastEditTime 。 有许多类似的问题但我的限制是我只能使用/修改 where 子句。 例如 我也无法修改选择查询。 像这样考虑它
select * from student, student_changed <-- *this part cannot be changed*
where <-- This can be modified
答案 0 :(得分:0)
尝试此查询:
select roll_no,name, max(LastEditTime)
from table2
group by
roll_no,name;
更新1:
select table1.roll_no,table1.name, max(table2.LastEditTime)
from table2 join table1 on table1.roll_no=table2.roll_no
group by
table1.roll_no,table1.name;
一张表足以满足您的要求。
更新2:
select table1.roll_no,table1.name, max(table2.LastEditTime)
from table2 join table1
where table1.roll_no=table2.roll_no
group by table1.roll_no,table1.name;
更新3:
select table1.roll_no,table1.name,table2.LastEditTime
from table2 join table1
where
(table1.roll_no,table1.name,table2.lastEditTime) in (select table1.roll_no,table1.name, max(table2.LastEditTime) from table2 join table 1 on table1.roll_no=table2.roll_no
group by table1.roll_no,table1.name);
答案 1 :(得分:0)
您不需要加入。表student_changed
就是您所需要的:
select roll_no, name, max(LastEditTime) as LastEditTime
from student_changed
group by roll_no, name
答案 2 :(得分:0)
感谢所有答案,但我设法通过以下where子句使其工作。
where student.roll_no = student_changed.roll_no
and LASTEDITTIME in(select max(LASTEDITTIME) from student_changed where student.roll_no = student_changed.roll_no)