需要SQL条件的帮助

时间:2015-10-06 04:11:58

标签: sql oracle join

假设我有两个表lpn和lpn_detail 如果我们在lpn表中使用lpn_id,我们将只获得一条记录。 如果我们在lpn_detail表中使用lpn_id,我们将获得多条记录,或者我们可能只获得一条记录。

当我们加入这两个表时,我需要一个条件,Lpn_Detail的多个记录只能作为结果获取。

select * from lpn inner join LPN_DETAIL
on lpn.lpn_id = lpn_detail.lpn_id
where 1=1
and lpn.LPN_FACILITY_STATUS='30' 
and lpn.INBOUND_OUTBOUND_INDICATOR='I';

3 个答案:

答案 0 :(得分:0)

您的查询没问题。 如果您只想选择特定列,请在选择查询中使用列名而不是*。

select col1,col2,col3 from lpn inner join LPN_DETAIL
on lpn.lpn_id = lpn_detail.lpn_id
where 1=1
and lpn.LPN_FACILITY_STATUS='30' 
and lpn.INBOUND_OUTBOUND_INDICATOR='I';

答案 1 :(得分:0)

您的查询没问题,您必须编写LPN_DETAIL。*而不是*才能获取LPN_DETAIL列。你可以把它写成:

select LPN_DETAIL.* from lpn inner join LPN_DETAIL
on lpn.lpn_id = lpn_detail.lpn_id
where 1=1
and lpn.LPN_FACILITY_STATUS='30' 
and lpn.INBOUND_OUTBOUND_INDICATOR='I';

答案 2 :(得分:0)

如果您只需要具有多个LPN_DETAIL的记录用于相同的LPN,则可以使用任一子查询:

select * from lpn inner join LPN_DETAIL
on lpn.lpn_id = lpn_detail.lpn_id
where 1=1
and lpn.LPN_FACILITY_STATUS='30' 
and lpn.INBOUND_OUTBOUND_INDICATOR='I'
and lpn_detail.lpn_id in (select lpn_id 
                            from lpn_detail 
                           group by lpn_id 
                          having count(*)>1);

或分析函数:

select * from(
select lpn.*,lpn_detail.*,
       count(*) OVER (partition by lpn_detail.lpn_id) cnt
from lpn inner join LPN_DETAIL
on lpn.lpn_id = lpn_detail.lpn_id
where 1=1
and lpn.LPN_FACILITY_STATUS='30' 
and lpn.INBOUND_OUTBOUND_INDICATOR='I')
where cnt>1;