SQL查询但基于另一个查询消除了一些记录

时间:2016-10-07 20:53:13

标签: sql

我可以遍历以下查询生成的表

Select userid_fk as id, courseID_fk 
from tbl_userCourse 
inner join tbl_users 
        on user_id=userid_fk 
where courseID_fk=5

然后摆脱一些记录,其中以下sql结果为空(我必须传入$ user_id)。我可以使用php使用此查询在网页上执行此操作。

Select min(schDate) as min 
from tbl_schedule 
where userid_fk=".$user_id." 
  and schDate>getDate()  
  and courseID_fk=5

但是现在我想知道我是否能以某种方式组合这两个sql语句并且只使用一个查询语句。如果是这样,我该怎么做?

2 个答案:

答案 0 :(得分:1)

使用存在

Select userid_fk as id, courseID_fk 
from tbl_userCourse 
inner join tbl_users 
        on user_id=userid_fk 
where courseID_fk=5
and exists (
    Select * 
    from tbl_schedule 
    where tbl_schedule.userid_fk = tbl_userCourse.userid_fk
      and tbl_schedule.schDate>getDate()  
      and tbl_schedule.courseID_fk=5
)
如果大括号之间的查询至少有一条记录,则

Exists返回true,因此and exits (...)将“跳过”该子查询为空的那些记录。

如您所见,此查询非常易读,因为它类似于您想要的内容

答案 1 :(得分:0)

您应该使用联接

Select tbl_userCourse.userid_fk as id, tbl_userCourse.courseID_fk , min(schDate)
from tbl_userCourse 
inner join tbl_users on tbl_users.user_id=userid_fk 
inner join tbl_schedule  on tbl_schedule.user_id =  tbl_users.user_id
where tbl_userCourse.courseID_fk=5
and tbl_userCourse.courseID_fk=tbl_schedule.courseID_fk
and schDate>getDate()

或者如果需要分组,那么

Select userid_fk as id, courseID_fk , min(schDate)
from tbl_userCourse 
inner join tbl_users on tbl_users.user_id=userid_fk 
inner join tbl_schedule  on tbl_schedule.user_id =  tbl_users.user_id
where tbl_userCourse.courseID_fk=5
and tbl_userCourse.courseID_fk=tbl_schedule.courseID_fk
and schDate>getDate()
group by tbl_userCourse.userid_fk , tbl_userCourse.courseID_fk