Employee Table:
Empid FNAme LName Hair Race
1 john adam 1 1
2 clift susanne 2 3
Code Table:
code type description
1 hair black
2 hair brown
1 race black
3 race white
我们需要将输出数据作为empid, Fname, Lname, Hair, Race
;
其中hair
和race
未显示为代码,但描述形成代码表。
我是sql的初学者。您可以帮忙写一个查询 我没有得到每个查询以下的预期输出
select E.Empid,E.FName,E.Lname,c.description as Hair,c.description as race
From Employee2 E inner join code c
on (c.code = E.Hair )
答案 0 :(得分:5)
您应该加入代码表两次:
SQL声明
SELECT E.EmpID
, E.FName
, E.LName
, c1.Description AS Hair
, c2.Description AS Race
FROM Employee E
INNER JOIN Code c1 ON c1.Code = e.Hair AND c1.type = 'hair'
INNER JOIN Code c2 ON c2.Code = e.Race AND c2.type = 'race'
请注意,如果其中任何一个可能是NULL
,您就可以将INNER JOIN
更改为LEFT OUTER JOIN
说,我建议你为Hair and Race 创建一个单独的代码表。
尝试将所有内容转储到一个代码表中只会让人感到困惑并迫使您最多编写次优查询。您强制自己将类型添加到代码表以及您将要创建的每个联接。
更好的选择是
Employee Table:
Empid FNAme LName Hair Race
1 john adam 1 1
2 clift susanne 2 3
HairCode Table:
code description
1 black
2 brown
RaceCode Table:
1 black
3 white
将您的陈述简化为
SELECT E.EmpID
, E.FName
, E.LName
, c1.Description AS Hair
, c2.Description AS Race
FROM Employee E
INNER JOIN HairCode c1 ON c1.Code = e.Hair
INNER JOIN RaceCode c2 ON c2.Code = e.Race
您将获得更好的性能和更小的足迹。
答案 1 :(得分:2)
您可以加入两次以获取所需的数据
select E.Empid, E.FName, E.Lname, hair.description as Hair, race.description as race
From Employee2 E
inner join code hair on (hair.code = E.Hair and hair.type = 'hair' )
inner join code race on (race.code = E.Race and race.type = 'race')