oracle从多个表中选择

时间:2018-06-01 14:18:34

标签: oracle plsql

如果p_search_string与那些字段相同,我的函数将返回mi home或者远离。

    FUNCTION SEARACH_FOR_GAMES  ( p_search_string in varchar2 )
                             return weak_cur
  IS
    SEARCH_FIXID WEAK_CUR;   
  BEGIN  
    OPEN   SEARCH_FIXID FOR
select  HOME,AWAY,COMP_NAME, M_TIME from SOCCER s
where s.HOME LIKE (:p_search_string) or s.AWAY LIKE (:p_search_string)
union all
select  HOME,AWAY,LISTS,M_TIME from BASKETBALL b
where b.HOME LIKE (:p_search_string) or b.AWAY LIKE (:p_search_string)
union all
select HOME,AWAY,COMP,M_TIME from HANDBALL h
where h.HOME LIKE (:p_search_string) or h.AWAY LIKE (:p_search_string)
union all
select  HOME,AWAY,LISTS,M_TIME from ICE_HOCKEY i
where i.HOME LIKE (:p_search_string) or i.AWAY LIKE (:p_search_string)
union all
select  HOME,AWAY,COMP,M_TIME from TENISt
where t.HOME LIKE (:p_search_string) or t.AWAY LIKE (:p_search_string)
union all
select  HOME,AWAY,LISTS,M_TIME from VOLLEYBALL v
where v.HOME LIKE (:p_search_string) or v.AWAY LIKE (:p_search_string);
    RETURN SEARCH_FIXID;
  END SEARACH_FOR_GAMES;

这很好用,但我想知道是否有更好的"写下这些选择的方法?

由于

1 个答案:

答案 0 :(得分:1)

就这个要求而言,这绝对是数据模型的一个问题。我可以提出两个选择:

选项#1: 通过组合所有表创建单个表SPORTS并具有列sport_type。这将允许在函数中使用一个选择查询。

select  HOME,AWAY,COMP_NAME, M_TIME from SPORTS s
where s.HOME LIKE (:p_search_string) or s.AWAY LIKE (:p_search_string)
  and sport_type in 
(
'SOCCER',
'BASKETBALL',
'HANDBALL',
'ICE_HOCKEY',
'TENIST',
'VOLLEYBALL'
)

选项#2:

Create a view by combining all these tables and select from that view in this function.
CREATE OR REPLACE VIEW VW_SPORTS
AS
select HOME,AWAY,COMP_NAME, M_TIME, 'SOCCER' SPORT_TYPE from SOCCER
union all
select  HOME,AWAY,LISTS,M_TIME,'BASKETBALL' SPORT_TYPE from BASKETBALL 
union all
select HOME,AWAY,COMP,M_TIME,'HANDBALL' SPORT_TYPE from HANDBALL
union all
select  HOME,AWAY,LISTS,M_TIME,'ICE_HOCKEY' SPORT_TYPE from ICE_HOCKEY
union all
select  HOME,AWAY,COMP,M_TIME,'TENIST' SPORT_TYPE from TENISt
union all
select  HOME,AWAY,LISTS,M_TIME,'VOLLEYBALL' SPORT_TYPE  from VOLLEYBALL v;


 FUNCTION SEARACH_FOR_GAMES  ( p_search_string in varchar2 )
                             return weak_cur
  IS
    SEARCH_FIXID WEAK_CUR;   
  BEGIN  
    OPEN   SEARCH_FIXID FOR
       select  HOME,AWAY,COMP_NAME, M_TIME from VW_SPORTS s
        where s.HOME LIKE (:p_search_string) or s.AWAY LIKE (:p_search_string)
         and s.SPOR_TYPE IN 
    (
    'SOCCER',
    'BASKETBALL',
    'HANDBALL',
    'ICE_HOCKEY',
    'TENIST',
    'VOLLEYBALL'
    );
    RETURN SEARCH_FIXID;
  END SEARACH_FOR_GAMES;