2016-11-03 30 views
0

我想解決如何計算用戶搜索是否匹配新發布的作業。作業提醒,檢查保存的每個作業的搜索以返回各自的用戶ID

我打算從一個JobID開始,回去查找所有具有保存搜索的用戶標識。

Jobs 

JobID WorkingHoursID JobTypeID AlertChecked 
4  1    1   0 
5  3    4   0 

UserJobSearches 

UserID JobSearchID Saved Alert SearchName 
1  2043  1  1  User1 
2  2044  1  1  User2 

Job Searches 

JobSearchID  SearchDate    Radius 
2043   2016-10-27 12:42:19  NULL 
2044   2016-10-27 12:43:19  NULL 

​​
JobSearchJobTypes 

JobSearchID JobTypeID 
2043  1 
2044  1 

-- get UserIDs from UserJobSearches using JobsearchID from sub query 
Select UserID FROM UserJobSearches WHERE JobSearchID IN(

    -- get jobsearch id from jobsearches 
    SELECT JobSearchID FROM JobSearches WHERE JobSearchID IN(

     -- get the WorkingHoursID 
     SELECT JobSearchID FROM JobSearchWorkingHours WHERE (
      WorkingHoursID IS NULL 
      OR 
      WorkingHoursID IN (
       SELECT WorkingHoursID FROM Jobs WHERE JobID = 4 
      ) 
     ) 

    ) AND JobSearchID IN(

     -- get the JobTypeID 
     SELECT JobSearchID FROM JobSearchJobTypes WHERE (
      JobTypeID IS NULL 
      OR 
      JobTypeID IN(
       SELECT JobTypeID FROM Jobs WHERE JobID = 4 
      ) 
     ) 

    ) 

) 

我的問題是圍繞排除搜索,如果它有一個條件,不完全匹配。 我還需要說,如果搜索不包含字段不排除結果

所以我幾乎需要說取得WorkingHoursID和JobSearchID的WHERE它匹配的搜索或不包括?

我已經多次嘗試爲此寫東西。但不斷髮現自己陷入困境和困惑。任何意見或幫助將不勝感激!

回答

1

Somethig類似會工作。您需要使用INNER JOIN加入所有搜索條件,然後可以選擇加入匹配LEFT OUTER JOIN的作業。最後再次加入Jobs表以獲得所有結果。隨着搜索條件的增加,有更好的方法可以做到這一點,但是,對於兩種搜索條件來說,這應該沒問題。

SELECT 
    UserID, 
    JobSearchID, 
    JobID, 
    MatchesHours=CASE WHEN X.MatchesHoursJobID IS NULL THEN 0 ELSE 1 END, 
    MatchesJobType=CASE WHEN X.MatchesJobTypeJobID IS NULL THEN 0 ELSE 1 END 
FROM 
(
    SELECT 
     UserID, 
     JobSearchID, 
     MatchesHoursJobID=CASE WHEN HoursMatch.JobID IS NULL THEN 0 ELSE 1 END, 
     MatchesJobTypeJobID=CASE WHEN JobTypeMatch.JobID IS NULL THEN 0 ELSE 1 END 
    FROM 
     UserJobSearches UJS 
     INNER JOIN JobSearches JS ON JS.JobSearchID=UJS.JobSearchID 
     INNER JOIN JobSearchJobTypes JSJT ON JSJT.JobSearchID =UJS.JobSearchID 
     INNER JOIN JobSearchWorkingHours JSWH ON JSWH.JobSearchID =UJS.JobSearchID 
     LEFT OUTER JOIN Jobs HoursMatch ON Jobs.WorkingHoursID=JSWH.WorkingHoursID 
     LEFT OUTER JOIN Jobs JobTypeMatch ON Jobs.JobTypeID =JSWH.JobTypeID 
)AS X 
INNER JOIN Jobs ON Jobs.JobID=MatchesHoursJobID OR Jobs.JobID=MatchesJobTypeJobID 
+0

這是非常感謝羅斯。不幸的是,有超過100K的記錄和許多更多的搜索條件:(只是簡化爲SO。你能指點我閱讀/如何實現這個沒有聯接的例子嗎? – atoms

+0

如果是這樣的話,我會建立一個臨時對於每個標準,添加與臨時表相匹配的作業,然後制定您的結果 –

+0

感謝羅斯,被告知一次完成一個JobID會更有效率。再次觸摸它,我想同樣的原則可以適用於?NB我已經找出瞭如何檢查null。已經更新了我的答案。感覺不需要改變現在就開始工作,你認爲它可能嗎? – atoms