为什么结果影响左连接表造船厂

时间:2011-06-08 05:40:33

标签: php mysql sql

这里我用左连接表造船厂写了一个查询。没有与此表相关的连接,但是当我们加入或删除时它会影响结果,问题是为什么? 主要影响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

非常感谢.....

3 个答案:

答案 0 :(得分:1)

使用子查询而不是使用连接。至少对于一些琐碎的联接。

答案 1 :(得分: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

使用左连接计数查询到Table2

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

结果:

-----------
2

答案 2 :(得分:0)

根据评论,这意味着您拥有从造船厂到造船厂的1对多关系,这些关系属于您的加入标准。这应该通过select distinct来解决。

修改应在您的计数语句

中应用distinct