2009-10-01 204 views
0

我有一個問題,讓這個SQL狀態返回我想要的: 我希望它返回一個屬性列表的僱員或Job_Profile。如果其中一人不具備的特性,應該在該行返回NULL /列 現在的SQL是這樣的:SQL JOIN和WHERE語句

SELECT Parameter.Patameter_Description ParamName, 
     Job_Profile.Title, Job_Property.Mark JobMark, 
     Emp_Property.Mark EmpMark, 
     Emp_Id--, (Employee.First_Name + ' ' + Employee.Last_Name) EmpName 
FROM Job_Property 
INNER JOIN Job_Profile ON Job_Profile.Title = Job_Property.Job_Title 
INNER JOIN Parameter ON Job_Property.Parameter_Id = Parameter.Id 
RIGHT JOIN Emp_Property ON Emp_Property.Parameter_Id = Job_Property.Parameter_Id 
INNER JOIN Employee ON Emp_Property.Emp_Id = Employee.Enterprise_Staff_Id 

WHERE Employee.Enterprise_Staff_Id = 22 
AND Job_Profile.Title = 
    (SELECT 
     Employee.Job_Profile_Name 
     FROM Employee WHERE Employee.Enterprise_Staff_Id = 22) 

結果是:

Analyse test 1 3 22 

而且我想它是是這樣的:

Analyse  test  1  3  22 

Data  test  3  NULL NULL or 22 

economic test  4  NULL NULL or 22 

Service  test  2  NULL NULL or 22 

我知道有我一個問題: - 加入Emp_Property - 使WHERE語句

回答

3

試着加入Emp_Property

+0

我嘗試這樣做,使用LEFT OUTER JOIN代替RIGHT JOIN,結果我得到了相同的是一樣的。 我也嘗試使所有的聯接全部和運行它沒有where子句,我仍然沒有得到我期望的NULL值 – Jorn 2009-10-01 10:41:37

0

當丹尼同意LEFT OUTER JOIN,使用「LEFT OUTER JOIN」的方法,而不是「INNER JOIN」因爲這隻會返回其中一個條目,這兩個表中找到行。

1

我找到了解決辦法,我不得不做出臨時表,並加入他們的行列:

CREATE TABLE #CompareJob 
(Parameter_Id INT 
,Parameter_Name VARCHAR(MAX) 
,Jobprofile VARCHAR(30) 
,Job_Mark INT 
) 
INSERT INTO #CompareJob(Parameter_Id,Parameter_Name, Jobprofile ,Job_Mark) 
    SELECT Parameter.Id, Parameter.Patameter_Description, Job_Profile.Title, Job_Property.Mark 
    FROM Job_Property 
    INNER JOIN Job_Profile ON Job_Profile.Title = Job_Property.Job_Title 
    INNER JOIN Parameter ON Job_Property.Parameter_Id = Parameter.Id 
    WHERE Job_Profile.Title = (SELECT Employee.Job_Profile_Name FROM Employee WHERE Employee.Enterprise_Staff_Id = 22) 

CREATE TABLE #CompareEmp 
(Parameter_Id INT 
,Parameter_Name VARCHAR(MAX) 
,Emp_Id INT 
,Emp_Name VARCHAR(100) 
,Emp_Mark INT 
) 
INSERT INTO #CompareEmp(Parameter_Id,Parameter_Name, Emp_Id , Emp_Name ,Emp_Mark) 
    SELECT Parameter.Id, Parameter.Patameter_Description, Employee.Enterprise_Staff_Id, (Employee.First_Name + ' ' + Employee.Last_Name) empname, Emp_Property.Mark 
FROM Emp_Property 
INNER JOIN Employee ON Employee.Enterprise_Staff_Id = Emp_Property.Emp_Id 
INNER JOIN Parameter ON Parameter.Id = Emp_Property.Parameter_Id 
WHERE Employee.Enterprise_Staff_Id = 22 

SELECT * FROM #CompareJob 
FULL OUTER JOIN #CompareEmp ON #CompareJob.Parameter_Id = #CompareEmp.Parameter_Id