sql server 2008 - What Join should I use in SQL -


i have 4 tables in database: person contains id(pk) , name. person_skill contains id(pk), pid(fk), skill(fk) , skilllevel(fk). skill contains id(pk) , skilllabel. skilllevel contains id(pk) , name.

every skill has level 0 7

now want display skill person has(include skilllevel = 0)

select    [dbo].person.name name,    [skill].skilllabel skillname,    [person_skill].[skilllevel] skilllevel    ([dbo].person inner join [dbo].[person_skill] on [dbo].[person_skill].pid= person.id)    inner join [dbo].[skill] on [dbo].[person_skill].skill=skill.id 

the above code display skill person has level 1 level 7.

i believe reason skill level 1 7 because person table contains skill level 1 7, i'm not sure this. got database other. if assumption correct, there anyway this? skills in skill table , display skill level person has(include skillllevel =0).

sample data: person id    name ---------- 1     michael 2     alex  person_skill id    pid  skillid skill_level 5     1     10          5 6     2     11          1 7     1     12          7 8     1     13          5  skill id    name 10    java 11    c++ 12    html 13    asp 14    c 15    .net 16    c# 17    objective  expect results are; name    skillname skilllevel ---------------------------- alex    java        0 alex    c++         1 alex    html        0 alex    asp         0 alex    c           0 alex    .net        0 alex    c#          0 alex    objective c 0 michael    java      5 michael    c++       0 michael    html      7 michael    asp       0 michael    c         0 michael    .net      5 michael    c#        0 michael    objective c0 

the current query output

alex    c++         1 michael    java      5 michael    html      7 michael    .net      5 

edit, if want return skill names each person, want use:

select d.p_name,   d.s_name skillname,   coalesce(ps.skill_level, 0) skill_level (   select p.id p_id, p.name p_name, s.id s_id, s.name s_name   person p   cross join skill s ) d left join person_skill ps   on d.p_id = ps.pid   , d.s_id = ps.skillid left join skill s   on ps.skillid = s.id 

see sql fiddle demo

if want include skills 0-7, want use left join. query similar following:

select p.name name,    s.skilllabel skillname,    ps.[skilllevel] skilllevel [dbo].[skill] s left join [dbo].[person_skill] ps   on ps.skill=s.id left join [dbo].person p   on ps.pid = p.id 

edit, without seeing data difficult determine. if want retrieve skilllevels, need include table. might need use:

select    p.name name,   s.skilllabel skillname,   sl.[name] skilllevel skilllevel sl left join [dbo].[person_skill] ps   on ps.skilllevel=sl.id left join [dbo].[skill] s   on ps.skill = s.id left join [dbo].person p   on ps.pid = p.id 


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -