我有以下 2 个表:
表1
[schoolName] [Track] [Student Name] [Program ID]
ABC 103 joe 1
ABC 101 Edward 2
QWE 103 Adam 5
QWE 103 Ben 1
表2
[SchoolName] [Program ID] [Class ID] [Class Name]
ABC 1 1 Science
ABC 1 2 Math
ABC 1 3 History
ABC 2 1 Science
QWE 5 1 Science
QWE 5 2 Math
QWE 1 2 Math
希望选择参加 track#103 programs not cover class#3 的学生姓名,并为他们的类(class)名称返回 NULL,如下结果:
[schoolName] [Track] [Student Name] [Program ID] [Class Name]
QWE 103 Adam 5 NULL
QWE 103 Ben 1 NULL
我正在尝试以下查询但它不起作用:
select Table1.[schoolName], Table1.[Track], Table1.[Student Name], Table1.[Program ID], Table2.[Class Name]
from table1, table2
where Table1.[schoolName]=Table2.[SchoolName]
and Table1.[Program ID]=Table2.[Program ID]
and Table1.[Track]=103
and Table2.[Class ID] = 3
OR Table2.[Class ID] IS NULL
我做错了什么?
最佳答案
首先,我非常怀疑您使用的是 MySQL
还是 Oracle
。引用 []
是特定于 SQL Server 的。
Looking to select student names attending track# 103 programs not covering class# 3 and return NULL for their class name
您可以首先从 table1
中获取所有记录,其中 track
为 103,然后使用相关子查询来消除程序包含 class id
= 3 的行:
SELECT T1.[schoolName],
T1.[Track],
T1.[Student Name],
T1.[Program ID],
NULL AS [Class Name]
FROM table1 T1
WHERE T1.[Track] = 103
AND NOT EXISTS (SELECT 1
FROM table2 T2
WHERE T1.[SchoolName] = T2.[SchoolName]
AND T1.[Program ID] = T2.[Program ID]
AND T2.[Class ID] = 3);
考虑使用不带空格的列名,例如 Program_ID、Class_ID
等。
关于mysql - 协助 SQL 查询返回不匹配的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35669721/