我已经在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
现在,我知道我需要将表连接在一起,我已经构建了表格,以便grade表包含连接到student和模块表的外键。
作为初学者,这种类型的查询很难让我难以理解,我希望我接近答案,这就是我所拥有的:
SELECT * FROM student WHERE studentID LIKE '10%' INNER JOIN grades
ON student.studentID=grades.studentID INNER JOIN module
ON grades.moduleID =module.moduleID
当然它不起作用,但我是沿着正确的轨道吗?这个问题的正确解决方案是保存在代码工具箱中以供以后使用的好方法!
答案 0 :(得分: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'
<强>结果强>
| STUDENTID | LASTNAME | FIRSTNAME | ------------------------------------ | 10356844 | Black | Roger |
答案 1 :(得分: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'
要进一步了解联接,请访问以下链接:
RESULT
╔═══════════╦══════════╦═══════════╦══════════╦═══════╦═════════════════════╗
║ STUDENTID ║ LASTNAME ║ FIRSTNAME ║ MODULEID ║ GRADE ║ MODULENAME ║
╠═══════════╬══════════╬═══════════╬══════════╬═══════╬═════════════════════╣
║ 10356844 ║ Black ║ Roger ║ CE1183 ║ B ║ Intelligent Systems ║
╚═══════════╩══════════╩═══════════╩══════════╩═══════╩═════════════════════╝