2012-11-14 134 views
0

我需要編寫一個有點複雜的查詢來放在一起。基本思想是匹配來自不同表格的幾個字段,然後根據結果編輯另一個表格。複雜的SQL查詢

有三個表涉及:

時間表:sch_id, date, schedule, event_id

Link_Location_Schedules:id, loc_id, sch_id

Link_Location_Events:id, loc_id, event_id

現在我需要嘗試做的是:

  1. 查找在「時間表」中今天的日期之後設置的時間表。
  2. 這些時間表從Link_Location_Events獲取位置ID,其中event_ids等於計劃事件ID。
  3. 對於每個匹配的時間表(sch_id)和返回的地點(loc_id),檢查該對是否已存在於Link_Location_Schedules中,如果不插入它們。

下面是我對上面做了一些SQL查詢,我只需要他們一些如何結合:

  1. SELECT sch_id FROM 'Schedules' WHERE DATE_FORMAT(sports_schedule_insert_date_time, "%Y-%m-%d") >= '2012-11-14';

  2. SELECT loc_id from Link_Location_Events, Schedules WHERE Link_Location_Events.event_id = Schedules.event_id;

回答

0

聽起來選擇語句中的簡單插入...

insert into Link_Location_Schedules 
    (loc_id, 
    sch_id) 
select 
     PreQuery.loc_id, 
     PreQuery.sch_id 
    from 
     (select 
       s.sch_id, 
       lle.loc_id 
      from 
       Schedules s 
       join Link_Location_Events lle 
        on s.event_id = lle.event_id) PreQuery 
     LEFT JOIN Link_Location_Schedules lls 
     on PreQuery.loc_id = lls.loc_id 
     and PreQuery.sch_id = lls.sch_id 
    where 
     lls.loc_id is null 

最內在的預先查詢是獲取所有可能的日程安排/位置ID。從那裏,左加入現有的地點/時間表上找到的人。然後,WHERE子句將只返回那些不匹配的地方(因此lls.loc_id爲空)。獲取該結果並直接插入到日程表/位置表中。

+0

謝謝你的回答...我不認爲我能想出這個。我會試一試。 – Paul

+0

它適用於現場。謝謝 :) – Paul