【问题标题】:Database Query Help needed需要数据库查询帮助
【发布时间】:2021-10-05 00:21:52
【问题描述】:

这就是我拥有的数据库:https://imgur.com/EmQm9vx

自从我上次使用 MySQL 数据库以来已经有一段时间了,所以我有一些问题需要解决。

首先,我需要编写一个查询,该查询可以显示学生的姓名和他们注册的班级。我在 WHERE 上尝试了一些东西,但我迷路了很多。

解决方案:使用 JOIN 是可行的方法,因为您需要连接 3 个表。

【问题讨论】:

  • 请与创建表和插入数据脚本共享示例数据。图像将不起作用。此外,每个帖子一个问题。
  • 在单独的帖子中提出您的其他问题。
  • 您标记了outer join,但仅当您想要没有相应班级的学生和/或没有相应学生的班级时才使用。您需要指定该要求。如果只希望匹配项坚持[INNER] JOIN,其中INNER 关键字是可选的。

标签: mysql sql database mysql-workbench outer-join


【解决方案1】:

从第一个问题开始。我们有一个多对多的关系,其中 student_class 将每个 student_id 与 class_id 链接起来,但名称存储在链接的学生表和班级表中。所以我们需要连接所有三个表。

SELECT student.name, class.name
  FROM student
  JOIN student_class
    ON student.id = student_class.student_id
  JOIN class
    ON class.id = student_class.class_id
;

【讨论】:

    【解决方案2】:

    你需要根据studentID把student表和class_registration表内联,然后根据classID把class_registration表和class表连接起来。

    SELECT student.Name, class.ClassName
      FROM student
      inner join class_registration 
        ON student.id = class_registration.StudentId
     inner join class
        ON class.classid = class_registration.ClassId
    ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      相关资源
      最近更新 更多