Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql Q:将2个查询合并为1个查询_Sql_Oracle_Oracle11g - Fatal编程技术网

Sql Q:将2个查询合并为1个查询

Sql Q:将2个查询合并为1个查询,sql,oracle,oracle11g,Sql,Oracle,Oracle11g,目前我有3个表: 用户表 用户名|姓|姓 课程表 课程id |课程名称|课程日期|课程描述 考勤表 课程id |用户名 用户表包含有关用户的信息。 课程表包含有关课程的信息。 有多个课程名称相同,但日期不同。 考勤表包含课程用户的考勤 我得到了用户名和课程名称的列表。我必须找到每个用户的名字和姓氏,以及每个用户参加课程的最新日期 目前,我首先使用此查询查找名字和姓氏 Select firstname, lastname from user where username in (<user

目前我有3个表:

用户表

用户名|姓|姓

课程表

课程id |课程名称|课程日期|课程描述

考勤表

课程id |用户名

用户表包含有关用户的信息。 课程表包含有关课程的信息。 有多个课程名称相同,但日期不同。 考勤表包含课程用户的考勤

我得到了用户名和课程名称的列表。我必须找到每个用户的名字和姓氏,以及每个用户参加课程的最新日期

目前,我首先使用此查询查找名字和姓氏

Select firstname, lastname from user where username in (<user list>)
接下来,我循环查看上一个查询的结果,并获取以下查询的第一个结果:

select date from attendance, course 
where attendance.course_id in (select course_id from course where course_name = <course>) 
and username = <username> and attendance.course_id = course.course_id 
order by course_date desc  
所有这些的结果是,对于n个用户,我必须运行n+1个查询。我想把这个问题简化为一个问题,有什么建议吗

谢谢

这是我的解决方案

Select 
  u.firstname
 ,u.lastname
 ,(Select Max(c.course_date) 
   from Attendance a
   join Course c on
   c.course_id = a.course_id
   where
   a.username = u.username
   and c.course_name = <course>
) latest_date
from user u
where u.username in (<user list>);

我是这样理解这个问题的:

select u.firstname, 
       u.lastname, 
       max(c.course_date) max_course_date
from t_attendance a join t_course c on c.course_id = a.course_id
                    join t_user u on c.username = u.username
where a.username in ('user1', 'user2', ...)
  and c.course_name in ('course1', 'course2', ...) 
group by u.firstname, 
         u.lastname;

WHERE子句可能需要调整,这取决于您如何获得用户名和课程名列表。

示例数据和所需结果将非常有用。