2011-06-08 49 views
1

在這裏,我用左連接表造船廠編寫了一個查詢。沒有與此表相關的連接,但它在加入或刪除時影響結果,問題是爲什麼? 主要影響OrderBook和TotalShips列。爲什麼影響左連接表造船廠的結果

select a.sbwynum, 
     a.sbnam, 
     a.deleted, 
     sum(if ((sh.statuscod = 'O' or sh.statuscod = 'S') and (left (
     condeldat, 4) = '2011' or left (adjdeldat, 4) = '2011' or left (
     deldat, 4) = '2011'), sh.cgt, 0)) as CurrCgt, 
     count(if ((sh.statuscod = 'O' or sh.statuscod = 'S') and (left (
     condeldat, 4) = '2011' or left (adjdeldat, 4) = '2011' or left (
     deldat, 4) = '2011'), 1, NULL)) as CurrShips, 
     count(if (sh.statuscod = 'O', 1, NULL)) as OrderBook, 
     count(if (sh.statuscod = 'S', 1, NULL)) as TotalShips, 
     a.country as coucod, 
     ct.counam, 
     a.fulnam, 
     a.status, 
     a.stoclist, 
     if (sh.statuscod = 'O', 1, 2) as StatusFlag 
from shipbuilder as a 
     left join 
     (select sbwynum, statuscod, condeldat, adjdeldat, deldat, cgt from 
     `ship` s join shiptype st on s.wytypid = st.wytypid and st.forsearch 
     = 'Y' and st.searchsb = 'Y' and deleted = 'N') sh on sh.sbwynum = 
     a.sbwynum 
     left join country ct on ct.coucod = a.country and ct.deleted = 'N' 
     left join shipyard sy on a.sbwynum = sy.sbwynum and sy.deleted != 'Y' and 
     sy.syclsid != 'B' 
where a.sbwynum != '' and 
     a.deleted = 'N' and 
     a.status != 'FV' and 
     a.country = '365' 
group by a.sbwynum 
having a.deleted = 'N' 
order by sbnam 

非常感謝.....

+0

內如何當它包含它影響到它,少結果或多個結果被應用?你有沒有嘗試過SELECT DISTINCT,看看是否仍然給出不同的結果?有幾個原因可能會導致這種情況發生: – 2011-06-08 05:48:48

+0

當我刪除其獲取更少的訂單和總計,反之亦然。 – Bajrang 2011-06-08 05:52:50

回答

0

基礎上的評論,這意味着你有一個1到從造船到船塢多關係的聯接條件落入。這應該用一個獨特的選擇來解決。

編輯的不同應該將計報表

+0

所有記錄都不同,但我已添加但不影響結果。 – Bajrang 2011-06-08 07:20:44

+0

問題是你的計數語句,這是不明顯的,嘗試改變它計數(如果(不同sh.statuscod ='O',1,NULL)),我不知道這是否會工作,雖然,作爲在概念驗證中,添加一列,然後在另一列不存在的情況下計數:count(distinct sh。statuscod),count(sh.statuscod) – 2011-06-08 08:46:54

+0

只是爲了感興趣,你是如何解決這個問題的? – 2011-06-08 10:05:41

1

而不是使用的連接使用子查詢。至少對於一些微不足道的加入。

+0

任何其他的想法,而不使用子查詢。 – Bajrang 2011-06-08 06:07:03

1

問題是爲什麼?

因爲你身上有shipyard多個行具有相同的sbwynum其中deleted != 'Y' and syclsid != 'B'

更新:

這是試圖解釋我的意思的例子。

表設置:

create table Table1 
(
    ID int, 
    Name varchar(10) 
) 

create table Table2 
(
    ID int, 
    IDFromTable1 int 
) 

表數據:無

insert into Table1 values (1, 'Name') 

insert into Table2 values (1, 1) 
insert into Table2 values (2, 1) 

數查詢左連接:

select count(T1.ID) 
from Table1 as T1 

結果:

----------- 
1 

左數查詢加入到表2

select count(T1.ID) 
from Table1 as T1 
    left outer join Table2 as T2 
    on T1.ID = T2.IDFromTable1 

結果:

----------- 
2 
+0

其實造船廠的表格左連接到shipbuilder表,所以它不應該影響shipbuilder表的記錄是一個基表,並且orderbook和totalship列是從sh別名子查詢(虛擬表)計算的,所以它不會影響計數的記錄。那麼你的答案根據條件哪裏適合。任何疑問 ? – Bajrang 2011-06-09 11:08:27

+0

@ J.J以我的意思爲例來更新答案。 – 2011-06-09 11:21:50