【问题标题】:SQL Query but Eliminate Some Records based on another QuerySQL 查询但基于另一个查询消除了一些记录
【发布时间】:2016-10-08 05:31:45
【问题描述】:

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

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 语句组合起来,只使用一个查询语句。如果是这样,我该怎么做?

【问题讨论】:

  • 请重新阅读您的问题。 “下面的 sql 导致为空”这句话让我感到困惑
  • 表示sql输出0行

标签: sql


【解决方案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 (...) 将“跳过”子查询为空的那些。

如您所见,此查询非常易读,因为它与您解释的内容相似

【讨论】:

  • 谢谢,返回所有行,不知道为什么。
  • 我在该表中有一个名为 schID 的 ID
  • 我在 SSMS 中运行它并抛出错误 Invalid column name 'id'。
  • 请看一下,我在 now 子查询中使用整个表名...现在可以用了吗?
  • 实际上,我看到子查询的输出为空...我看看能不能把它放到 sqlfiddle 中,我会告诉你...谢谢你的帮助。跨度>
【解决方案2】:

你应该使用连接

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    相关资源
    最近更新 更多