2014-11-24 25 views
1

我有一個表task,其中包含例如更新查詢以修復兩個表之間的錯誤引用

task_id group_id plantype 
1  0   1 
13  1   0 
14  1   0 
15  1   0 

這表明任務13,14,15下任務1.
plantype分組也表明,如果我們面對的是一羣與否。

我有一個第二表用於任務(N-1)allocations含有分配,即,其還包含字段task_id

有在allocations記錄錯誤地指向組記錄(較早的轉換即具有遺體錯誤):

alloc_id  task_id 
xxx   1 

他們應該在該組中指向「第一」的任務,「第一」是最低task_id

alloc_id  task_id 
xxx   13 

如何構建我的更新查詢?

違規的分配是很容易找到,因爲團體不能有分配:

select a.alloc_id,t.task_id from alloc a, task t 
where a.task_id=t.task_id 
and coalesce(t.plantype,0) = 1 

我需要的task_id離那裏爲group_id確定min(task_id)的, 和我需要的allocid S選擇分配記錄更新

確定最低task_id一組:

select group_id,min(task_id) as task_min_id 
from task 
group by group_id 

組裝它一起,它開始看起來像:

update alloc 
set task_id = 
    (
    select min(task_id) as task_min_id 
    from task 
    where group_id = 
     (
     select t.task_id from alloc a, task t 
     where a.task_id=t.task_id 
     and coalesce(t.plantype,0) = 1 
    )   
    group by group_id 
    ) 

where alloc_id in 
    (
    select a.alloc_id from alloc a, task t 
    where a.task_id=t.task_id 
    and coalesce(t.plantype,0) = 1 
) 

,但我在這裏擱淺。這本身給出了一個「多行單身選擇」的錯誤。我曾嘗試過放入其他/更多表別名,但我懷疑alloc a, task t上的兩個子語會無論如何都會同步。

我的查詢應該是什麼?

我現在在Firebird中嘗試,但我必須在SQL Server和Oracle中使用此工作。

回答

2

這有兩個部分。一個是獲取正確的記錄進行更新。 。我認爲你可以in使用子查詢(或使用exists)做到這一點,另一種是update我相信下面將SQL Server和Oracle,可能火鳥工作:

update allocations a 
    set task_id = (select min(t.task_id) 
        from task t 
        where t.group_id = a.task_id and 
         t.planttype = 0 
       ) 
    where a.task_id in (select t.task_id from task t where t.planttype = 1); 
+0

謝謝。我得到你爲什麼有這麼多金徽章;-) – 2014-11-25 09:09:17

0

我認爲這會工作:

update allocations a1 
    set task_id = 
    (
select min (task_id) 
    from task 
    where group_id = a1.task_id);