【问题标题】:how do you search Right/Left joins?你如何搜索右/左连接?
【发布时间】:2009-08-04 17:22:07
【问题描述】:

我在搜索多个表时遇到问题 ,我有 2 张桌子

tbl课程

-课程编号

-名称

-状态

tblenroll

-courseid(持有tblcourse的courseid)

-学生号

假设一个学生的学生编号为 1990,他在 tblenrol 注册了 2 门课程

我想知道 1990 的课程名称和他没有订阅的课程名称

我得到的最接近的是对 tblcourses 的右外部连接,然后我得到了我想要的结果,但是一旦我附加了 where 子句,它就不会给我其他没有得到他的学号的课程。

任何帮助!

编辑(从 op 发布的答案中添加)

您好,谢谢您的回复。好吧,我不认为我解释得当。

tblcourse 将举办许多课程 tblenroll 拥有许多注册

所以,假设我们有 6 门课程。学生 1990 注册 3 个,学生 1880 注册 1 个(1990 没有选择的)

当我们运行这个时:

WHERE (tblenroll.studentid = 1990 or tblenroll.studentid is null)

where e.studentid is null or  e.studentid is not null and e.studentid = 1990

它将选择 5 门课程,3 门注册到 1990 年,2 门 NULLS。第六个注册到1880年。

此查询带来正确的结果,但不适用于特定学生

SELECT
    tblenroll.studentid as stud,
    tblcourse.name,
    tblenroll.studentid,
    tblenroll.courseid,
    tblcourse.courseid,
FROM
    tblenroll
Right Join tblcourse ON tblenroll.courseid = tblcourse.courseid 

有了上面我会得到

1880 - 1 1990 - 3 空 - 2

令人困惑的东西!

【问题讨论】:

    标签: sql join


    【解决方案1】:
    select tblcourse.name, e.studentid
    from tblcourse c left join tblenroll e on c.courseid = e.courseid
    where e.studentid is null or  e.studentid is not null and e.studentid = :id
    

    这会导致

    course1 1990
    course2 NULL
    course3 NULL
    course4 1990
    ...
    

    根据您的数据库,您可以使用一种 IIF 函数来放置 1 或 0、true 或 false - 任何标志作为第二个元素

    【讨论】:

      【解决方案2】:

      您可能只需要让 studentid 以及您要查询的实际 id 为 null。

      试一试,例如:

      SELECT tblenroll.studentid, tblcourse.courseid, tblcourse.name, tblcourse.status
      FROM tblenroll RIGHT OUTER JOIN tblcourse ON tblenroll.courseid = tblcourse.courseid
      WHERE (tblenroll.studentid = 1990 
      or tblenroll.studentid is null) -- this allows the courses in which 1990 is not enrolled
      

      编辑:我第一次没想到这一点。上面的查询是我天真的方法,可能返回的结果与 OP 想要的结果相同。诀窍不是在表连接后使用 where 子句,而是限制 tblenroll 中参与连接的行。

      我相信这应该可行(我在 SQL Server 2005 上使用类似的表/结构对其进行了测试):

      SELECT tblenroll.studentid, tblcourse.courseid, tblcourse.name, tblcourse.status
      FROM tblenroll RIGHT OUTER JOIN tblcourse ON tblenroll.courseid = tblcourse.courseid
          AND tblenroll.studentid = 1990
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-28
        • 1970-01-01
        • 2020-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-11
        相关资源
        最近更新 更多