0

我在 Stackoverflow 上研究了很多涵盖此类问题的问题,但我无法得到我寻求的解决方案。

这是我的表:

STUDENT
studentID   lastName   firstName
08422567    Brown      Susan
10356844    Black      Roger
10659475    White      Steven
09463729    Grey       Naomi


MODULE
moduleID   moduleName
CE1181     Biometrics
CE1183     Intelligent Systems
CE1133     Databases
CE1186     HCI

GRADES
studentID*  moduleID*  grade
10356844    CE1181     A
10356844    CE1183     B
10356844    CE1133     C
10356844    CE1186     A
08422567    CE1181     B
08422567    CE1183     B
08422567    CE1133     B
08422567    CE1186     B
10659475    CE1181     C
10659475    CE1183     C
10659475    CE1133     A
10659475    CE1186     C
09463729    CE1181     A
09463729    CE1183     B
09463729    CE1133     B
09463729    CE1186     B

我需要运行的查询是:

Select all from students whose id begins with 10 and their grade for intelligent systems was a B

现在,我知道我需要将表连接在一起,我已经构建了我的表,以便成绩表包含连接到学生表和模块表的外键。

作为初学者,这种类型的查询很难解决,我希望我接近答案,这就是我所拥有的:

SELECT * FROM student WHERE studentID LIKE '10%' INNER JOIN grades
ON student.studentID=grades.studentID  INNER JOIN module
ON grades.moduleID =module.moduleID

当然它不起作用,但我是否走在正确的轨道上?将这个问题的正确解决方案保存在代码工具箱中以供以后使用是一件很棒的事情!

4

2 回答 2

3

快到了,但WHERE需要JOIN遵循条款。我使用别名来简化语法。

SELECT s.* 
FROM   grades g 
       JOIN module m 
         ON m.moduleid = g.moduleid 
       JOIN student s 
         ON s.studentid = g.studentid 
WHERE  g.studentid LIKE '10%' 
       AND g.grade = 'B' 
       AND m.modulename = 'Intelligent Systems' 

结果

| 学生证 | 姓氏 | 名字 |
----------------------------------
| 10356844 | 黑色 | 罗杰 |

查看演示

于 2013-03-11T00:28:33.530 回答
1

WHERE子句应该跟在FROM子句之后。

SELECT  a.*, b.*, c.*   -- deselect the columns you don't want to show
FROM    student a
        INNER JOIN grades b
            ON a.studentID = b.studentID  
        INNER JOIN module c
            ON b.moduleID = c.moduleID
WHERE   a.studentID LIKE '10%' AND
        b.grade = 'B' AND
        c.modulename = 'Intelligent Systems' 

要进一步了解有关联接的更多信息,请访问以下链接:

结果

╔═══════════╦══════════╦═══════════╦══════════╦═══════╦═════════════════════╗
║ STUDENTID ║ LASTNAME ║ FIRSTNAME ║ MODULEID ║ GRADE ║     MODULENAME      ║
╠═══════════╬══════════╬═══════════╬══════════╬═══════╬═════════════════════╣
║  10356844 ║ Black    ║ Roger     ║ CE1183   ║ B     ║ Intelligent Systems ║
╚═══════════╩══════════╩═══════════╩══════════╩═══════╩═════════════════════╝
于 2013-03-11T00:27:23.287 回答