根据多个条件选择一列(多对多关系)

时间:2012-05-26 11:00:52

标签: sql ms-access join many-to-many

好吧,我知道标题可能有点不清楚,但我找不到更好的标题。让我解释一下情况,

我有3张桌子(实际上很多,但是对于这个例子我们需要3张) 1. teachers表格,其中包含teacherid, teachername, other columns (DOB etc)...列 2. classes表格,其中包含classid, classname, other columns (students in class etc)列 3. subjects表格,结构为subjectid, subjectname, other columns (unimportant at this point)

现在正如你可以从桌子上猜测的那样,存在多对多的关系,因为一个教师可以教许多课程,一个教师可以教很多科目,一个班可以有很多科目等等。所以包含这些多对多关系的表格是..
4. ClassSubjectClassId, SubjectId, CustomRemark
5. TeacherSubjectTeacherId, SubjectId, CustomRemark
6. TeacherClassTeacherId, ClassId, CustomRemark

您可能会猜到,表4表示哪个类具有哪些主题(前两个列标记为主键)的映射。表5表示教师可以教什么科目(前两个col标记为pk),表6再代表教师可以教什么班级。 (我只希望我足够明确,不要混淆你!)

现在的问题是,我有一个字典,Dictionary<int, Dictionary<int, List<int>>> dctClsSubTeachers以给定的顺序存储,类的id,每个类的id,另一个包含subject的id的字典,以及该课程的ID,如果是主题,可以在相应的课程中教授该主题的教师列表。 (这可能听起来有点复杂,但请仔细考虑一下我相信它会有意义:(

所以,我需要填充这个字典,因此我需要一个查询思想,我可以提供classId和subjectId作为参数,我得到一个所有教师的列表,不仅可以教这个主题,而且在参数中给出的课程中教授该课程(我们有关系表4,5和6),因此我可以填充该字典

你知道吗,我已经尝试了很多方法,但是没有一种方法可行,我试过的是一对......

select teacherId from teachers where teacherid in (SELECT teacherid from teacherclass where classid = k
intersect
SELECT teacherid from teachersubject where subjectid = k2) // I can't use this because access doesn't support intersect

我试过的另一个

SELECT teacherid
FROM Teachers, (ClassSubject INNER JOIN TeacherClass ON ClassSubject.ClassId = TeacherClass.ClassId) INNER JOIN TeacherSubject ON ClassSubject.SubjectId = TeacherSubject.SubjectId;

我已经尝试了几次,但是不能这样做,经过10小时的头痛,我以为stackoverflow!那么,有人可以,请帮帮我吗?

ps:如果您需要进一步澄清数据库(或其他任何内容),请随时询问..
pps:我正在使用ms-access 2007而且由于某些原因,我无法迁移到sql server

3 个答案:

答案 0 :(得分:1)

尝试使用JOIN:

SELECT tc.TeacherId
FROM ClassSubject
INNER JOIN TeacherSubject ON TeacherSubject.SubjectId = ClassSubject.SubjectId
INNER JOIN TeacherClass ON TeacherClass.TeacerId = TeacherSubject.teacherId AND ON TeacherClass.ClassId = ClassSubject.ClassId
WHERE ClassSubject.ClassId = [Your ClassId]
AND ClassSubject.SubjectId = [Your SubjectId]

答案 1 :(得分:0)

试试这个

Select TeacherSubject.TeacherId From TeacherSubject 
INNER JOIN ClassSubject ON TeacherSubject.SubjectID=ClassSubject.SubjectID
INNER JOIN TeacherClass ON Teacherclass.ClassID=TeacherSubject.ClassID
Where TeacherClass.ClassID=1 AND ClassSubject.SubjectID=1

当然是MSS SQL语法。我认为对于MS ACCESS,你必须使用JOIN。要再次从教师课程中获取教师姓名,您需要将此教师ID加入教师课程。

答案 2 :(得分:-1)

呀! 我实际上已经解决了! 这是解决方案..

SELECT Classes.ClassId, Classes.ClassName, Subjects.SubjectId, Subjects.SubjectName, Teachers.TeacherId, Teachers.TeacherName
FROM (Teachers INNER JOIN (Classes INNER JOIN TeacherClass ON Classes.ClassId = TeacherClass.ClassId) ON Teachers.TeacherId = TeacherClass.TeacherId) INNER JOIN (Subjects INNER JOIN TeacherSubject ON Subjects.SubjectId = TeacherSubject.SubjectId) ON Teachers.TeacherId = TeacherSubject.TeacherId
where classes.classid = k and subjects.subjectid = p
GROUP BY Classes.ClassId, Subjects.SubjectId, Teachers.TeacherId, classes.classname, subjects.subjectname, teachers.teachername;