【问题标题】:What kind of JOIN statements would retrieve the correct data from 3 tables?什么样的 JOIN 语句可以从 3 个表中检索正确的数据?
【发布时间】:2018-04-03 13:35:59
【问题描述】:

我目前正在开发一个类似于学校报告系统的 VB.NET 项目。为了这个问题,我想从 3 个表中检索数据。下面详细介绍了它们的字段...

(Table CoursesTakes) | TakeID(Primary),StudentID(Foreign),CourseID(Foreign),TargetGrade

(Table Courses) | CourseID(Primary),CourseName

(Table Reports) | ReportID(Primary),CourseTakeID(Foreign),CurrentGrade,ReportNumber

(Table Students) |  StudentID(Primary),StudentName

下面的图表可能会有所帮助...

我现有的系统需要一个特定 SID 的输入。然后,我可以使用 CT 表的 SELECT 查询来检索相应的 CID 和 TargetGrade。此外,我可以检索每个学生 CT 的 CGrade 和 RNumber 字段。

我面临的问题是设计我需要的查询,该查询可以为每个学生的特定课程提供相应的 CourseName、CGrade、TargetGrade 和 RNumber。我知道 inner 、 right 和 left 连接,但将其应用于 3 个表被证明是一个挑战。任何建议将不胜感激,我愿意接受任何问题。

谢谢大家。

【问题讨论】:

  • 在表上使用内连接会遇到什么问题?你能告诉我们你尝试了什么吗?
  • 我目前拥有的是 2 个单独的内部连接语句,它们为我提供了 2 个单独的数据集。 1 包含学生的课程名称和目标成绩,而另一个仅包含当前成绩和报告编号。我面临的问题是找到正确的语句,将 4 个字段中的数据放入单个数据集中,因为我在尝试将正确的课程名称、目标等级、当前等级和报告编号链接到单个数据集中时遇到了当前系统的障碍.
  • 请编辑您的问题并包含您已经提出的一个或多个查询。
  • 问题不一定在于我的查询,而在于我需要使用的连接设计,以便从这 4 个字段中检索数据

标签: mysql sql vb.net phpmyadmin


【解决方案1】:

您将使用 INNER JOIN 在各自的/共享键上将您的表连接在一起。类似于以下内容:

SELECT
    Students.StudentID,
    Students.Studentname,
    Courses.CourseName,
    CoursesTakes.TargetGrade,
    Reports.CurrentGrade,
    Reports.ReportNumber
FROM
    Students
    INNER JOIN CoursesTakes ON Student.StudentID = CoursesTakes.StudentId
    INNER JOIN Courses ON CoursesTakes.CourseID = Courses.CoursesID
    INNER JION Reports ON CoursesTakes.TakeID = Reports.CourseTakeID
WHERE
    Students.StudentID = <yourstudentid>

如果这不能回答问题,那么请分享一些示例数据和您想要的结果,以便我们了解您的数据的结构。

【讨论】:

  • 这看起来解决了我面临的困境。非常感谢!
  • 我的荣幸!祝你的项目好运!
【解决方案2】:

您可以尝试完全加入来检索所有记录:

select 
    Student.*, CourseTake.*, courses.*,Report.* 
from 
    students 
full join  
    CourseTake on Student.ID == CourseTake.StudentID
full join  
    Courses on Courses.id == CourseTake.StudentID
full join  
    Report on CourseTake.ID = CourseTake.Take ID

【讨论】:

    猜你喜欢
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    相关资源
    最近更新 更多