我有一个带有两个父表的数据库,这些表由连接表中的外键引用,我正在试图弄清楚如何从一个父表中获取所有相关行,并给出一个值另一个。 例如,使用以下表格和列:
schoolA_courses:
id
course_prefix
course_number
schoolB_courses:
id
course_prefix
course_number
schoolB_equivalencies:
equivalency_id
schoolA_id
schoolB_id
FOREIGN KEY (schoolA_id) REFERENCES schoolA_courses (id)
FOREIGN KEY (schoolB_id) REFERENCES schoolB_courses (id)
看起来像这样的行:
schoolA:
1, MATH, 101
2, SOCI, 100
3, HIST, 211
schoolB:
1, MATH, 100
2, MATH, 110
3, ENGL, 210
schoolB_equivalencies:
1, 1, 1 (school A's MATH 101 equivalent to school B's MATH 100)
2, 1, 2 (school A's MATH 101 equivalent to school B's MATH 110)
给定一个schoolA课程前缀和数字(比方说MATH 101),如何构建SELECT查询以查找schoolB_equivalencies
表中列为等效的所有schoolB课程前缀/数字对?例如,通过我的MATH 101虚拟课程,我将如何获得
MATH 100
MATH 110
答案 0 :(得分:1)
此查询获取有关原始课程的信息:
SELECT *
FROM schoolA
WHERE course_prefix = 'MATH'
AND course_number = 101;
此查询获取有关联结表中相应行的信息:
SELECT *
FROM schoolB_ueqivalencies
WHERE schoolA_id = (SELECT id
FROM schoolA
WHERE course_prefix = 'MATH'
AND course_number = 101);
此查询获取有关schoolB
:
SELECT *
FROM schoolB
WHERE id IN (SELECT schoolB_id
FROM schoolB_ueqivalencies
WHERE schoolA_id = (SELECT id
FROM schoolA
WHERE course_prefix = 'MATH'
AND course_number = 101));