我有 2 个表:候选人
和 工作
。
在Jobs
中,有Profession
和Subprofession
列。
对于候选
中的每一行,有 8 列:
Selected_Profession1, Selected_Subprofession1,
Selected_Profession2, Selected_Subprofession2,
Selected_Profession3, Selected_Subprofession3,
Selected_Profession4, Selected_Subprofession4
我想进行一个查询,选择其职业和副职业位于 Candidates
表中相应字段之一的所有职位。
假设我们有以下 Jobs 表:
(profession subprofession) -----> (100, 200)
(100, 201)
(101, 200)
(101, 201)
以及以下候选表:
(prof1 subprof1 prof2 subprof2 prof3 subprof3 prof4 subprof4) ---->
(100, 200, 300, 400, 100, 200, 100, 300)
(101, 200, 102, 200, 300, 200, 200, 300)
(100, 200, 300, 400, 101, 201, 100, 300)
(101, 101, 200, 200, 300, 300, 400, 400)
该查询将从 Jobs 表返回第 1、3 和 4 行(因为候选者 1 具有 100、200 对,候选者 2 具有 101、200 对,候选者 3 具有 101、201 对)。
希望这足够清楚......
最佳答案
您可以使用 or
条件对多个字段进行联接:
select j.*
from jobs j join
candidates c
on (j.prof = c.prof1 and j.subprof = c.subprof1) or
(j.prof = c.prof2 and j.subprof = c.subprof2) or
(j.prof = c.prof3 and j.subprof = c.subprof3) or
(j.prof = c.prof4 and j.subprof = c.subprof4);
如果你有很大的表,那么性能不会很好。您可以通过使用 CandidateProf
表来修复数据结构以获得更好的性能,其中每个 prof/subprof 对位于不同的行。
利用您拥有的数据结构,通过每个教授/副教授分组的单独联接,您将获得更好的性能,特别是通过在该对上建立索引。问题在于 select
子句。所以:
select distinct j.*
from jobs j lef outer join
candidates c1
on (j.prof = c1.prof1 and j.subprof = c1.subprof1) left outer join
candidates c2
on (j.prof = c2.prof2 and j.subprof = c2.subprof2) left outer join
. . .
where c1.prof1 is not null or c2.prof1 is not null or
c3.prof1 is not null or c4.prof1 is not null
并且您需要删除重复项,因为一名候选人可能拥有多项资格。
关于sql - 按 2 个类别和多个列内连接 2 个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16760148/