连接两个表,一个表具有父子层次结构,并且输出给出的行多于表1

时间:2020-04-24 02:23:21

标签: sql duplicates

   select b.top_lvl_itm_num,
    b.grp_lvl_itm_num,
    b.cmpnt_lvl_itm_num,
    b.lvl,
    b.grp_lvl_plt,
    b.cmpnt_lvl_plt ,
    a.sys_category from v_lttt_cost b 
    left join v_lttt_sys_category_map a on b.top_lvl_itm_num=a.top_lvl_itm_num and 
    b.grp_lvl_itm_num=b.grp_lvl_itm_num and b.cmpnt_lvl_itm_num=b.cmpnt_lvl_itm_num and b.lvl=a.lvl

    where b.grp_lvl_itm_num='MV' and 
    b.cmpnt_lvl_itm_num="ON1433' and 
    b.lvl=12 and 
    b.grp_lvl_plt='1110'

这是我正在使用的代码。我应该只返回11行,但是给了我121行。左表有11行。

2 个答案:

答案 0 :(得分:0)

b.cmpnt_lvl_itm_num="ON1433'

在这里使用“ ON1433”“',应该有错误

答案 1 :(得分:0)

您在连接的两端都使用了相同的别名b,这会导致更多数据。

我修改了查询:

select b.top_lvl_itm_num,
    b.grp_lvl_itm_num,
    b.cmpnt_lvl_itm_num,
    b.lvl,
    b.grp_lvl_plt,
    b.cmpnt_lvl_plt ,
    a.sys_category 
from v_lttt_cost b 
left join v_lttt_sys_category_map a 
on b.top_lvl_itm_num=a.top_lvl_itm_num and 
   b.grp_lvl_itm_num=a.grp_lvl_itm_num and    
   b.cmpnt_lvl_itm_num=a.cmpnt_lvl_itm_num and 
   b.lvl=a.lvl
    where b.grp_lvl_itm_num='MV' and 
    b.cmpnt_lvl_itm_num='ON1433' and 
    b.lvl=12 and 
    b.grp_lvl_plt='1110'

更新:从您的评论看来,即使将LEFT JOIN放在那之后,您的数据也要乘以11倍,这意味着您有很多行(在这种情况下为11行)在右表中加入JOIN组合。如果您的数据中有重复项,则可以放置DISTINCT子句以过滤出重复项。