使用一个表中的不同记录将其与其他表的不同条目组合

时间:2012-06-25 09:58:18

标签: sql sql-server join

我有两张桌子。员工和资格。

员工

Emp_id   Name   Qualification1   Qualification2    Qualification3
10001   xxxxxx         1              3                5
10002   yyyyyy         3              2                       
.......
......
.....

资格

Qual_ID   Qual_name
    1      B.Tech
    2      MCA
    3      M.Tech

如何使用连接查询获取以下输出

Emp_ID   Name    Qual1   Qual2   Qual3
10001   xxxxxxx  B.Tech   MCA     pppp
10002   yyyyyyy  B.Tech   
......
.....
.....

4 个答案:

答案 0 :(得分:5)

试试这个

Select E.Emp_ID,E.Name,Q1.Qual_Name,Q2.Qual_Name,
Q3.Qual_Name
From 
Employees AS E
INNER JOIN Qualifications As Q1 ON E.Qualification1=Q1.Qual_ID
INNER JOIN Qualifications As Q2 ON E.Qualification2=Q2.Qual_ID
INNER JOIN Qualifications As Q3 ON E.Qualification3=Q3.Qual_ID

答案 1 :(得分:3)

SELECT e.emp_id, 
       e.name, 
       q1.qual_name, 
       q2.qual_name, 
       q3.qual_name, 
FROM   employee e 
       INNER JOIN qualifications q1 
               ON e.qualification1 = q1.qual_id 
       INNER JOIN qualifications q2 
               ON e.qualification2 = q2.qual_id 
       INNER JOIN qualifications q3 
               ON e.qualification3 = q2.qual_id 

答案 2 :(得分:3)

在此链接中查看实时工作示例:

SQLFiddle

这很好。

答案 3 :(得分:0)

试试这个:

Sql Fiddle

Select Emp_id, Name, (Select Qual_name from Qualifications where Qualifications.Qual_ID = Employee.Qualification1) as Qual1, (Select Qual_name from Qualifications where Qualifications.Qual_ID = Employee.Qualification2) as Qual2, (Select Qual_name from Qualifications where Qualifications.Qual_ID = Employee.Qualification3) as Qual3
From Employee