Joining 18 tables -- one at a time or in two stages ?? best one..??

I have to join 18 tables,.. Is it best to join all 18 in a single shot or to go with
multi stages-- 9 tables in one stage and after that anotther 9 tables..
Please anyone give me a good suggestion on this with some reason...
Thanks in advance

If you can look at your query and recognise that it is trying to collect (say) two small result sets and then join the result sets, then it is actually a good idea to express the query in that fashion to Oracle.
Take for example a query that sums last week's profits for a supermarket by department using a 9 table query in about 2 minutes. A similar query reports the previous week's profits with a marginally different query in about two minutes. You write the two queries as inline views and join them to report the percentage change in profit by department - and the query takes 4 hours because Oracle has used "complex view merging" to turn your two 9-table queries into a single 18-table query.
In this case, a workaround is to use the /*+ no_merge */ hint. In outline, something like:
select     {columns}
from
     select /*+ no_merge */
          dept_no,
          etc.
     from     ...
     )     lw,
     select /*+ no_merge */
          dept_no,
          etc.
     from     ...
     )     pw
where
     pw.dept_no = lw.dept_no
;In less obvious cases you may still be able to find that you can break up a big query into a few smaller, logical sections, and use this technique to generate and join what are, in effect, intermediate results.
An alternative to the /*+ no_merge */ hint is to use subquery factoring to the same end. There's a more complex example of the method here: http://jonathanlewis.wordpress.com/2007/07/01/internet-sql/
In either case, avoid turning your 18-table query into 18 separate pieces and sticking them back together - it may make the optimizer do some very silly things. Karen Morton mentions an example of this on her blog: http://karenmorton.blogspot.com/2008/06/dont-do-work-you-dont-have-to-do.html
Regards
Jonathan Lewis
http://jonathanlewis.wordpress.com
http://www.jlcomp.demon.co.uk
"The greatest enemy of knowledge is not ignorance,
it is the illusion of knowledge." (Stephen Hawking)

Similar Messages

  • Join 2 tables, One to many, but single row only

    I have a table (actually it is a view) with detail information.
    I want to join to that table, but for my join criteria, bring back no more than 1 row. This is because there is some data on the table which is consisitent on each row so any row of my join will do.
    ie.
    select list.invoice_number, inv.payment_terms
    from
    list, inv
    where list.invoice_number=inv.invoice_number(+)
    LIST
    Invoice Number
    1
    2
    3
    4
    INV
    Invoice Number, Seq, Payment_terms
    1               1    30
    1               2    30
    1               3    30
    2               1    40
    2               2    40
    3               1    50would produce
    Invoice Number, Payment_terms
    1               30
    2               40
    3               50
    4Thanks

    Would there be more than one value for payment_terms in inv? If so, then the distinct is probably the way to go, although I would probably do the DISTINCT in an in-line view like:
    SELECT list.invoice_number, inv.payment_terms
    FROM list,
         (SELECT DISTINCT invoice_number, payment_terms
          FROM inv) inv
    WHERE list.invoice_number=inv.invoice_number(+)If each invoice would only ever have one value for payment_terms, then I might try an in-line view like:
    SELECT list.invoice_number, inv.payment_terms
    FROM list,
         (SELECT invoice_number, MAX(payment_terms) payment_terms
          FROM inv
          GROUP BY invoice_number) inv
    WHERE list.invoice_number=inv.invoice_number(+)On the other hand, if inv is a view based on a multitable join, I would also check to see if incoice_number and payment_terms come from the same table. If so, I would be tempted to write your query using the base tables instead of the view since it is likely to bve more efficient.
    John

  • MKPF & MSEG Performance issue : Join on table  MKPF & MSEG  taking too much time ..

    Hello Experts,
    I had a issue where we are executing one custom report in which  i used inner join on table  MKPF & MSEG,  some time join statement  took  9-10 min to excute and some time execute within  1-2 min with same test data .
    i am not able to understand what the actaully happing .
    please help.
    code :
       SELECT f~mblnr f~mjahr f~usnam f~bktxt  p~bukrs
        INTO TABLE itab
        FROM mkpf AS f INNER JOIN mseg AS p
            ON f~mblnr = p~mblnr AND f~mjahr = p~mjahr
         WHERE f~vgart = 'WE'
           AND f~budat IN p_budat
           AND f~usnam IN p_sgtxt
           AND p~bwart IN ('101','105')
           AND p~werks IN p_werks
           AND p~lgort IN p_lgort.
    Regards,
    Dipendra Panwar.

    Hi Dipendra,
    if you call a report twice after another with the same test data for data selection, then the second run should be faster, because some data are remaining in memory and needn't to be caught from database. This will be also for the following third und further runs, until the data in the SAP memory will be removed by other programs.
    For performance traces you should try to test with a first run.
    Regards,
    Klaus

  • Left Outer Joining multiple tables to one source table FAILS with VLD-1511

    Hi all,
    Is it me, or is OWB unable to handle left outer joining 1 source table to multiple other tables?
    I want to load a fact table so I have 1 source table with measures. This table must be outer joined to some dimensions that have their FK in the fact table.
    The SQL statement would look like this (and is perfectly valid):
    select ...
    from input, dim1, dim2
    where input.c1 = dim1.c1(+)
    and input.c2 = dim2.c2(+);
    I put the where clause in the joiner operator and validate, but that gives me message VLD-1511: A table may be outer joined to at most one other table.
    Even splitting this up into one outer join per joiner still gives this message.
    A search and look around on the forum and on metalink shows there are related issues (like bug 3334035). Seemingly creating a view is the work-around to use.....? (ie downgrading owb to a simple gui tool) }-;
    Have other people experienced this problem of not being able to outer join one input table to multiple other tables?
    Thanks,
    Ed

    I have had some feedback from Oracle. It turns out this has to do with 2 issues. Below I have pasted the text that Support gave me:
    <---------- START QUOTE ---------->
    RESEARCH
    =========
    Bug 3437036 KEY LOOKUP DOES NOT DETECT ORA-1417 IN VALIDATE/GENERATE STEP
    Unpublished Bug 4211684 FORWARD PORT OF BUG 3437036
    shows:
    Some more development has been completed when this bug is fixed in Paris.
    The following are the details:
    1. If the join condition contains a full outer join such as
    tab1.c (+) = tab2.c (+) and tab2.c (+) = tab3.c
    then the new validations implemented for this bug do not apply since
    in OWB, full outer join triggers generation of joins in ANSI syntax.
    ANSI syntax does not have the original problem the base bug of this
    bug reported.
    2. If the join condition does not contain any full outer join condition,
    then the join is generated in Oracle join syntax, which is subject two
    several restrictions. The fix to this bug check two of the restrictions.
    3. The first restriction in Oracle syntax is that the outer join operator
    "(+)" can only directly be attached to a column name. If you attach it
    to an expression, such as the following:
    (tab1.c + 1) (+) = tab2.c
    Then there will be an ORA-936 error at the time of mapping deployment.
    For this case, I have added a validation message VLD-1512 to error out
    this situation.
    4. The second restriction in Oracle syntax is that a table can only be
    outer joined to exactly one other table.
    For example, this is an invalid join in Oracle syntax:
    tab1.c (+) = tab2.c and tab1.d (+) = tab3.d
    because tab1 is left outer joined to tab2 and tab3.
    But note that the following is still valid in Oracle syntax:
    tab1.c (+) = tab2.c and tab1.d = tab3.d (+)
    because tab1 is left outer joined to tab2 and right outer joined to tab3.
    So this latter case does not violate the restriction that "same oj" to
    more than 1 table is not allowed.
    If same oj to more than 1 table is specified in a join condition,
    VLD-1511 will be issued, and the map is made invalid.
    <---------- END QUOTE ---------->
    OWB does a partial validation, ie not all access paths are (can be) checked. A full check is only done by the database itself. So some scenarios (like checking whether multiple tables are outer joined the correct way) are not checked, and in this case are flagged with an error (even though it is actually a correct scenario).
    Seemingly this was not flagged with an error in earlier versions of OWB, so beware, OWB behaviour may change when upgrading...
    Alternative solutions are (1) using key lookups, (2) using a view with all outer joins in there, (3) using intermediate result tables between the joins.
    Hope this info helps some people prevent spending too much time on a false error message,
    Ed

  • Join same table 3 times, count from two other tables

    Hi all!
    I have 3 tables
    RECORDS
    Id, Record_Id
    ITEMS
    Id, Record_Id
    ARTICLES
    Id, Record_Id
    I need to join RECORDS table 3 times R1,R2,R3 and get count of items R2 and R3 have and count articles that R3 has.
    R2 must have ITEMS and R3 must have items, R3 may have articles. R1 may have multiple children and R2 may have multiple children.
    Solution I'm using is following, but distinct makes it slow...
    select r1 as ParentRecordId,count(distinct i1) as Volumes,count(distinct i2) as Numbers, count(distinct a1) as Articles
    from
        select r1.id as r1,i1.id as i1,i2.id as i2,a.id as a1
        from records r1 inner join records r2 on r1.id=r2.record_id
        inner join records r3 on r2.id=r3.record_id
        inner join items i1 on r2.id=i1.record_id
        inner join items i2 on r3.id=i2.record_id
        left join articles a on a.record_id=r3.id
    ) as sel
    group by r1
    order by 1
    Regards
    Meelis

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. And thanks for no sample, too! 
    >> I have 3 tables <<
    No, you have three identical decks of 1950's punch cards written in bad SQL. 
    There is no such thing as a generic, universal “id” in RDBMS. It has to be the identifier of something particular. 
    Magical columns appear in your query. 
    There is no such concept as “child' and “parent” in RDBMS. That was network and hierarchical databases. We have referenced and referencing tables. 
    We do not use column positions in the ORDER BY cause; any change in the query used in the cursor will screw up everything. 
    Would you like to try again? 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Reg: how to join more than one cluster table into one

    Hi gurus
    How to join more than one cluster table into one
    amk

    Hi,
    You cannot join cluster tables
    Best way is to select from the header table and then select from the item table table using for all entries of header table.
    regards,
    Advait

  • Network or database calls are made when joining more than one table

    Hi Friends,
    could anybody please let me know how may networks are called when joining more than one table.
    Thanks
    Rinky

    Hi Rinky,
      Normally when a JOIN between two database tables is made then following steps occur:-
    1) The control goes to database. Based on the JOINING and WHERE condition, an internal table is created in the DATABASE only which is filled. So here the computation is done at DATABASE level.
    2) Once the internal table is filled at database level, it is sent back to the application level.
    A Join operation normally minimizes the round trips to the database as most of the computation is done at database level only and results sent back to the Application layer.
    <b>Thus for a simple JOIN OPERATION makes a single DATABASE call.</b>
    NOTE: If you are satisfied with the explanation, then please reward points
               accordingly :).
    Thanks and regards,
    Ravi .

  • Using functions in select statement(joining 5 tables) taking long time in Oracle

    Hi,
    I have created a query in oracle which joins 5 tables and uses two functions(function names are 'ca_concat' and 'ca_concat_noseq').
    Query takes approximately 40 secs to execute around 12000 records. If I remove the functions from query it excutes within a second..
    Note : I have used the oracle SQL Developer for testing the query.
    It would be appriciated if anybody helps me to improve the perfomance of the query.
    Below are the querie with and without functions:
    1. Query with functions:
    select
    imsAuditEvent12.id as ID,
    imsAuditEvent12.audit_time as AUDIT_TIME,
    imsAuditEvent12.admin_dn as ADMIN_DN,
    imsAuditEvent12.admin_name as ADMIN_NAME,
    imsAuditEvent12.event_name as EVENT_NAME,
    imsAuditEvent12.event_description as EVENT_DESCRIPTION,
    imsAuditEvent12.event_state as EVENT_STATE,
    imsAuditEvent12.envname as ENVNAME,
    imsAuditTaskSession12.task_name as TASK_NAME,
    imsAuditTaskSession12.id as TASK_ID,
    imsAuditTaskSession12.task_description as TASK_DESCRIPTION,
    imsAuditTaskSession12.task_priority as TASK_PRIORITY,
    S1.OBJECT_ID,
    S1.OBJECT_NAME as OBJECT_NAME,
    S1.OBJECT_TYPE as OBJECT_TYPE,
    S2.ATTRIBUTE_NAME as ATTRIBUTE_NAME,
    S2.ATTRIBUTE_OLDVALUES as ATTRIBUTE_OLDVALUES,
    S2.ATTRIBUTE_NEWVALUES as ATTRIBUTE_NEWVALUES,
    S3.OBJECT_DN as OBJECT_DN,
    S3.OBJECT_TYPE as IMSOBJECT_TYPE,
    S3.CONTAINER_NAME as CONTAINER_NAME,
    S3.CONTAINER_DN as CONTAINER_DN,
    S3.CONTAINER_TYPE as CONTAINER_TYPE
    from
    imsAuditEvent12 LEFT JOIN imsAuditTaskSession12 ON imsAuditTaskSession12.id=imsAuditEvent12.tasksession_id LEFT JOIN
    (select parent_event_id,
    ca_concat('imsAuditEventObject12.parent_event_id',parent_event_id,'imsAuditEventObject12.object_name','imsAuditEventObject12') as OBJECT_NAME,
    ca_concat('imsAuditEventObject12.parent_event_id',parent_event_id,'imsAuditEventObject12.object_type','imsAuditEventObject12') as OBJECT_TYPE,
    ca_concat_noseq('imsAuditEventObject12.parent_event_id',parent_event_id,'imsAuditEventObject12.ID','imsAuditEventObject12') as OBJECT_ID
    from
    imsAuditEventObject12 group by parent_event_id) S1
    ON imsAuditEvent12.id = S1.parent_event_id LEFT JOIN
    (select
    parent_object_id,
    ca_concat('parent_object_id',parent_object_id,'attribute_name','imsauditobjectattributes12') as ATTRIBUTE_NAME,
    ca_concat('parent_object_id',parent_object_id,'attribute_oldvalue','imsauditobjectattributes12') as ATTRIBUTE_OLDVALUES ,
    ca_concat('parent_object_id',parent_object_id,'attribute_newvalue','imsauditobjectattributes12') as ATTRIBUTE_NEWVALUES
    from
    imsauditobjectattributes12 group by parent_object_id) S2
    ON S1.OBJECT_ID = S2.parent_object_id LEFT JOIN
    (select
    parent_event_id,
    ca_concat('parent_event_id',parent_event_id,'OBJECT_DN','imsauditobjectrelationship12') as OBJECT_DN,
    ca_concat('parent_event_id',parent_event_id,'OBJECT_TYPE','imsauditobjectrelationship12') as OBJECT_TYPE ,
    ca_concat('parent_event_id',parent_event_id,'CONTAINER_NAME','imsauditobjectrelationship12') as CONTAINER_NAME,
    ca_concat('parent_event_id',parent_event_id,'CONTAINER_DN','imsauditobjectrelationship12') as CONTAINER_DN,
    ca_concat('parent_event_id',parent_event_id,'CONTAINER_TYPE','imsauditobjectrelationship12') as CONTAINER_TYPE
    from
    imsauditobjectrelationship12 group by parent_event_id) S3
    ON imsAuditEvent12.id =S3.parent_event_id where imsauditevent12.id > 0 and imsauditevent12.id <12000 order by imsauditevent12.id ASC;
    2. Query without using functions:
    select * from imsauditeventobject12 left join imsauditevent12 on imsauditeventobject12.id=imsauditevent12.id left join imsauditobjectattributes12 on imsauditeventobject12.id=imsauditobjectattributes12.parent_object_id left join imsaudittasksession12 on imsauditevent12.tasksession_id=imsaudittasksession12.id left join imsAuditObjectRelationship12 on imsAuditEvent12.id =imsAuditObjectRelationship12.parent_event_id where imsauditevent12.id >0 and imsauditevent12.id < 12000 order by imsauditevent12.id asc;
    Thanks,
    Badri

    Hi,
    Please find the below more information about the query.
    DB version: Oracle 11g Enterprise Edition Release 11.2.0.1.0
    Below are source of the functions:
    create or replace function ca_concat( ca_key_name in varchar2,
                           ca_key_val  in varchar2,
                           ca_other_col_name in varchar2,
                           ca_tname     in varchar2 )
       return varchar2
          as
           type rc is ref cursor;
           l_str    varchar2(32000);
           l_sep    varchar2(1);
           l_val    varchar2(32000);
           l_count   number(6);
           l_cur    rc;
       begin
       l_count :=1;
       l_str := '';
           open l_cur for 'select '|| ca_other_col_name ||'
                             from '|| ca_tname || '
                            where ' || ca_key_name || ' = '
                       using ca_key_val;
           loop
               fetch l_cur into l_val;
               l_val := SUBSTR(l_val,0,102);
               exit when (l_cur%notfound or l_count > 38);
               l_str := l_str || l_sep || l_count || '.' || l_val;
               l_sep := ',';
           l_count := l_count + 1;
           end loop;
           close l_cur;
           return l_str;
       end;
      create or replace function ca_concat_noseq( ca_key_name in varchar2,
                           ca_key_val  in varchar2,
                           ca_other_col_name in varchar2,
                           ca_tname     in varchar2 )
       return varchar2
          as
           type rc is ref cursor;
           l_str    nvarchar2(32000);
           l_sep    varchar2(1);
           l_val    varchar2(32000);
           l_count   number(6);
           l_cur    rc;
       begin
       l_count :=1;
           open l_cur for 'select '||ca_other_col_name||'
                             from '|| ca_tname || '
                            where ' || ca_key_name || ' = '
                       using ca_key_val;
           loop
               fetch l_cur into l_val;
               exit when (l_cur%notfound or length(l_val)>3000 or l_count>1);
               l_str := l_str || l_sep || l_val ;
               l_sep := ',';
           l_count := l_count + 1;
           end loop;
           close l_cur;
           return l_str;
    end;
    Below are the tables structures:
    DESC imsauditevent12;
    Name                           Null     Type                                                                                                                                                                                      
    ID                             NOT NULL NUMBER                                                                                                                                                                                       
    TASKSESSION_ID                 NOT NULL NUMBER                                                                                                                                                                                       
    TASKSESSION_OID                         VARCHAR2(100)                                                                                                                                                                                
    PARENT_EVENT_OID                        VARCHAR2(100)                                                                                                                                                                                
    AUDIT_TIME                     NOT NULL TIMESTAMP(6)                                                                                                                                                                                 
    EVENT_OID                      NOT NULL VARCHAR2(100)                                                                                                                                                                                
    ADMIN_DN                       NOT NULL VARCHAR2(512)                                                                                                                                                                                
    ADMIN_NAME                              VARCHAR2(255)                                                                                                                                                                                
    EVENT_NAME                     NOT NULL VARCHAR2(255)                                                                                                                                                                                
    EVENT_DESCRIPTION                       VARCHAR2(4000)                                                                                                                                                                               
    EVENT_STATE                             VARCHAR2(100)                                                                                                                                                                                
    ENVNAME                        NOT NULL VARCHAR2(100)                                                                                                                                                                                
    ENV_OID                        NOT NULL VARCHAR2(100)                                                                                                                                                                                
    DESC imsauditeventobject12;
    Name                           Null     Type                                                                                                                                                                                         
    ID                             NOT NULL NUMBER                                                                                                                                                                                       
    PARENT_EVENT_ID                NOT NULL NUMBER                                                                                                                                                                                       
    AUDIT_TIME                     NOT NULL TIMESTAMP(6)                                                                                                                                                                                 
    OBJECT_TYPE                    NOT NULL VARCHAR2(100)                                                                                                                                                                                
    OBJECT_NAME                             VARCHAR2(255)                                                                                                                                                                                
    DESC imsauditobjectattributes12;
    Name                           Null     Type                                                                                                                                                                                         
    ID                             NOT NULL NUMBER                                                                                                                                                                                       
    PARENT_OBJECT_ID               NOT NULL NUMBER                                                                                                                                                                                       
    AUDIT_TIME                     NOT NULL TIMESTAMP(6)                                                                                                                                                                                 
    DISPLAY_NAME                            VARCHAR2(255)                                                                                                                                                                                
    ATTRIBUTE_NAME                 NOT NULL VARCHAR2(255)                                                                                                                                                                                
    ATTRIBUTE_OLDVALUE                      VARCHAR2(4000)                                                                                                                                                                               
    ATTRIBUTE_NEWVALUE                      VARCHAR2(4000)                                                                                                                                                                               
    DESC imsaudittasksession12;
    Name                           Null     Type                                                                                                                                                                                         
    ID                             NOT NULL NUMBER                                                                                                                                                                                       
    PARENT_TS_OID                           VARCHAR2(100)                                                                                                                                                                                
    PARENT_EVENT_OID                        VARCHAR2(100)                                                                                                                                                                                
    AUDIT_TIME                     NOT NULL TIMESTAMP(6)                                                                                                                                                                                 
    TASKSESSION_OID                NOT NULL VARCHAR2(100)                                                                                                                                                                                
    ADMIN_DN                       NOT NULL VARCHAR2(512)                                                                                                                                                                                
    ADMIN_NAME                              VARCHAR2(255)                                                                                                                                                                                
    TASK_NAME                               VARCHAR2(255)                                                                                                                                                                                
    TASK_TAG                       NOT NULL VARCHAR2(255)                                                                                                                                                                                
    TASK_DESCRIPTION                        VARCHAR2(4000)                                                                                                                                                                               
    TASK_PRIORITY                           NUMBER                                                                                                                                                                                       
    STATE                          NOT NULL VARCHAR2(100)                                                                                                                                                                                
    ENVNAME                        NOT NULL VARCHAR2(100)                                                                                                                                                                                
    ENV_OID                        NOT NULL VARCHAR2(100)                                                                                                                                                                
    DESC imsAuditObjectRelationship12;
    Name                           Null     Type                                                                                                                                                                                         
    ID                             NOT NULL NUMBER                                                                                                                                                                                       
    PARENT_EVENT_ID                NOT NULL NUMBER                                                                                                                                                                                       
    AUDIT_TIME                     NOT NULL TIMESTAMP(6)                                                                                                                                                                                 
    OBJECT_TYPE                    NOT NULL VARCHAR2(100)                                                                                                                                                                                
    OBJECT_DN                      NOT NULL VARCHAR2(512)                                                                                                                                                                                
    CONTAINER_TYPE                 NOT NULL VARCHAR2(100)                                                                                                                                                                                
    OBJECT_NAME                    NOT NULL VARCHAR2(255)                                                                                                                                                                                
    CONTAINER_NAME                 NOT NULL VARCHAR2(255)                                                                                                                                                                                
    CONTAINER_DN                   NOT NULL VARCHAR2(512)                                                                                                                                                                          
    OPERATION                      NOT NULL VARCHAR2(50)                                                                                                                                                                                 
    Thanks,
    Badri

  • How to insert into two differents tables at the same time

    Hi
    I'm newer using JDev, (version 3.1.1.2 cause the OAS seems to support just the JSP 1.0)
    and I want to insert into two differents tables at the same time using one view.
    How can I do that ?
    TIA
    Edgar

    Oracle 8i supports 'INSTEAD OF' triggers on object views so you could use a process similar to the following:
    1. Create an object view that joins your two tables. 'CREATE OR REPLACE VIEW test AS SELECT d.deptno, d.deptname, e.empname FROM DEPT d, EMP E'.
    2. Create an INSTEAD OF trigger on the view.
    3. Put code in the trigger that looks at the :NEW values being processed and determines which columns should be used to INSERT or UPDATE for each table. Crude pseudo-code might be:
    IF :NEW.deptno NOT IN (SELECT deptno FROM DEPT) THEN
    INSERT INTO dept VALUES(:NEW.deptno, :NEW.deptname);
    INSERT INTO emp VALUES (:NEW.deptno, :NEW.empname);
    ELSE
    IF :NEW.deptname IS NOT NULL THEN
    UPDATE dept SET deptname = :NEW.deptname
    WHERE deptno = :NEW.deptno;
    END IF;
    IF :NEW.empname IS NOT NULL THEN
    UPDATE emp SET empname = :NEW.empname
    WHERE deptno = :NEW.deptno;
    Try something along those lines.
    null

  • Is it possible to use a case statement when joining different tables based on input parameters?

    Hi,
    I have a scenario where my stored procedure takes 5 parameters and the users can pass NULL or some value to these parameters and based on the parameters, I need to pull data from various tables.
    Is it possible to use a case statement in the join, similar the one in the below example. I'm getting error when I use the below type of statement.
    select a.*
    from a
    case
    when parameter1=1 then
    inner join a on a.id = b.id
    when parameter1=2 then
    inner join a on a.id = c.id
    end;
    Please let me know, if this type of statement works, and if it works will it create any performance issues?. If the above doesn't work, could you please give me some alternate solutions?
    Thanks.

    Here's a technique for joining A to B or C depending on the input parameters. In theory, you are joining to both tables but the execution plan includes filters to skip whichever join is not appropriate. The drawback is that you have to do outer joins, not inner ones.
    CREATE TABLE A AS SELECT LEVEL ak FROM dual CONNECT BY LEVEL <= 100;
    CREATE TABLE b AS SELECT ak, bk
    FROM A, (SELECT LEVEL bk FROM dual CONNECT BY LEVEL <= 10);
    CREATE TABLE c(ak, ck) AS SELECT ak, bk*10 FROM b;
    variable p1 NUMBER;
    variable p2 NUMBER;
    exec :p1 := 1;
    exec :p2 := 20;
    SELECT /*+ gather_plan_statistics */ A.ak, nvl(b.bk, c.ck) otherk FROM A
    LEFT JOIN b ON A.ak = b.ak AND :p1 IS NOT NULL AND b.bk = :p1
    LEFT JOIN c ON A.ak = c.ak AND :p1 is null and :p2 IS NOT NULL and c.ck = :p2
    WHERE A.ak <= 9;
    SELECT * FROM TABLE(dbms_xplan.display_cursor(NULL,NULL,'IOSTATS LAST'));
    | Id  | Operation             | Name            | Starts | E-Rows | A-Rows |   A-Time   | Buffers |
    |   0 | SELECT STATEMENT      |                 |      1 |        |      9 |00:00:00.01 |       7 |
    |*  1 |  HASH JOIN OUTER      |                 |      1 |      9 |      9 |00:00:00.01 |       7 |
    |*  2 |   HASH JOIN OUTER     |                 |      1 |      9 |      9 |00:00:00.01 |       7 |
    |*  3 |    TABLE ACCESS FULL  | A               |      1 |      9 |      9 |00:00:00.01 |       3 |
    |   4 |    VIEW               | VW_DCL_5532A50F |      1 |      9 |      9 |00:00:00.01 |       4 |
    |*  5 |     FILTER            |                 |      1 |        |      9 |00:00:00.01 |       4 |
    |*  6 |      TABLE ACCESS FULL| B               |      1 |      9 |      9 |00:00:00.01 |       4 |
    |   7 |   VIEW                | VW_DCL_5532A50F |      1 |      9 |      0 |00:00:00.01 |       0 |
    |*  8 |    FILTER             |                 |      1 |        |      0 |00:00:00.01 |       0 |
    |*  9 |     TABLE ACCESS FULL | C               |      0 |      9 |      0 |00:00:00.01 |       0 |
    Predicate Information (identified by operation id):
       1 - access("A"."AK"="ITEM_0")
       2 - access("A"."AK"="ITEM_1")
       3 - filter("A"."AK"<=9)
      5 - filter(:P1 IS NOT NULL)
       6 - filter(("B"."AK"<=9 AND "B"."BK"=:P1))
       8 - filter((:P2 IS NOT NULL AND :P1 IS NULL))
       9 - filter(("C"."AK"<=9 AND "C"."CK"=:P2))
    You can see that table C was not really accessed: the buffer count is 0.
    exec :p1 := NULL;
    SELECT /*+ gather_plan_statistics */ A.ak, nvl(b.bk, c.ck) otherk FROM A
    LEFT JOIN b ON A.ak = b.ak AND :p1 IS NOT NULL AND b.bk = :p1
    LEFT JOIN c ON A.ak = c.ak AND :p1 is null and :p2 IS NOT NULL and c.ck = :p2
    WHERE A.ak <= 9;
    SELECT * FROM TABLE(dbms_xplan.display_cursor(NULL,NULL,'IOSTATS LAST'));
    Now table B is not accessed.
    | Id  | Operation             | Name            | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
    |   0 | SELECT STATEMENT      |                 |      1 |        |      9 |00:00:00.02 |       7 |      2 |
    |*  1 |  HASH JOIN OUTER      |                 |      1 |      9 |      9 |00:00:00.02 |       7 |      2 |
    |*  2 |   HASH JOIN OUTER     |                 |      1 |      9 |      9 |00:00:00.01 |       3 |      0 |
    |*  3 |    TABLE ACCESS FULL  | A               |      1 |      9 |      9 |00:00:00.01 |       3 |      0 |
    |   4 |    VIEW               | VW_DCL_5532A50F |      1 |      9 |      0 |00:00:00.01 |       0 |      0 |
    |*  5 |     FILTER            |                 |      1 |        |      0 |00:00:00.01 |       0 |      0 |
    |*  6 |      TABLE ACCESS FULL| B               |      0 |      9 |      0 |00:00:00.01 |       0 |      0 |
    |   7 |   VIEW                | VW_DCL_5532A50F |      1 |      9 |      9 |00:00:00.01 |       4 |      2 |
    |*  8 |    FILTER             |                 |      1 |        |      9 |00:00:00.01 |       4 |      2 |
    |*  9 |     TABLE ACCESS FULL | C               |      1 |      9 |      9 |00:00:00.01 |       4 |      2 |

  • Joining 3 tables in MySQL using PHP

    Hi,
    I have the following 3 sample tables:
    First
    idkey
    fk_second_idkey
    fk_third_idkey
    Second
    idkey
    Third
    idkey
    My SQL is
    SELECT * FROM First INNER JOIN Second ON First.fk_second_idkey = Second.idkey INNER JOIN Third First.fk_third_idkey = Third.idkey AND First.fk_second_idkey = 2;
    It compiles and I get a result set, but its repeated, so if i get back records 2, 3 and 4, the page will show 2, 3 and 4 about 3 times.
    Can anyone assist with the above SQL?
    Thanks.

    Just kind of guessing at what you're trying to do, but if you want it grouped by the first table (one result per first table ID), then something like:
    SELECT * FROM First
    INNER JOIN Second
       ON First.fk_second_idkey = Second.idkey
    INNER JOIN Third
       ON First.fk_third_idkey = Third.idkey
          AND First.fk_second_idkey = 2
    GROUP BY First.idkey;
    ...but I'm unclear on what's happening already and what you need it to do. Are the linked tables a one-to-one relationship? one-to-many?

  • Why oh why, weird performance on joining large tables

    Hello.
    I have a large table cotaining dates and customer data. Organised as:
    DATE CUSTOMER_ID INFOCOLUMN1 INFOCOLUMN2 etc...
    Rows per date are a couple of million.
    What I'm trying to do is to make a comparison between date a and date b and track changes in the database.
    When I do a:
    SELECT stuff
    FROM table t1
    INNER JOIN table t2
      ON t1.CUSTOMER_ID = t2.CUSTOMER_ID
    WHERE t1.date = TO_DATE(SOME_DATE)
    AND t2.date = TO_DATE(SOME_OTHER_DATE)I get a result in about 40 seconds which is acceptable.
    Then I try doing:
    SELECT stuff
    FROM (SELECT TO_DATE(LAST_DAY(ADD_MONTHS(SYSDATE, 0 - r.l))) AS DATE FROM dual INNER JOIN (SELECT level l FROM dual CONNECT BY LEVEL <= 1) r ON 1 = 1) time
    INNER JOIN table t1
      ON t1.date = time.date
    INNER JOIN table t2
      ON t1.CUSTOMER_ID = t2.CUSTOMER_ID
    WHERE t2.date = ADD_MONTHS(time.date, -1)Ie i generate a datefield from a subselect which I then use to join the tables with.
    When I try that the query takes an hour or two to complete with the same resultset as the first example.
    THe only difference is that in the first case I give the dates literally but in the other case I generate them in the subselect. It's the same dates and they are formatted as dates in both cases.
    Any ideas?
    Thanks
    Edited by: user1970293 on 2010-apr-29 00:52
    Edited by: user1970293 on 2010-apr-29 00:59

    When I try that the query takes an hour or two to complete with the same resultset as the first example.If you get the same results, than why change the query to the second one?
    THe only difference is that in the first case I give the dates literally but in the other case I generate them in the subselect. It's the same dates and they are formatted as dates in both cases.Dates are dates,... the formatting is just "pretty"
    This
    select to_date(last_day(add_months(sysdate
                                      ,0 - r.l)))
      from dual
    inner join (select level l from dual connect by level <= 1) r on 1 = 1doesn't make much sense... what is it supposed to do?
    (by the way: you are doing a TO_DATE on a DATE...)

  • Join 2 tables with 2 criteria

    hello
    i'm trying to join 2 tables with 2 criteria
    one criteria is  "numero de matricule" and the other is "date" 
    in one table i have many times the same "matricule"  it depends of "date de validité" validity date
    ex table 1
    n°mat - periode - montant
    1 -31-12-2013 -  100
    table2
    n°mat -periode - nom - adresse
    1 -
    31-12-2013 - gerard  - 12 RUE X
    1- 31/12/2012-GERARD - 2AVENUE Z
    how can i join those tow table
    thak you for your help, i'm a french beginner

    select *
    from table1 as a
    join table2 as b
    on a.n°mat = b.n°mat
    and a.periode = b.periode
    sqldevelop.wordpress.com
    Saeid, check this out and reply there if you're interested:
    http://social.technet.microsoft.com/Forums/en-US/a2e22d61-7c32-43f2-900e-d9d6325fa26d/needed-more-power-pivot-answerers?forum=sqlkjpowerpivotforexcel
    Thank you for all your contributions!
    Ed Price, Azure & Power BI Customer Program Manager (Blog,
    Small Basic,
    Wiki Ninjas,
    Wiki)
    Answer an interesting question?
    Create a wiki article about it!

  • How to join multiple tables !

    Give me the Example to join multiple tables 1

    Inner join
    IF p_bsart IS INITIAL.
    SELECT ekko~bukrs
    ekko~lifnr
    ekko~ebeln
    ekko~waers
    ekko~bsart
    ekko~ekorg
    ekko~ekgrp
    ekpo~ebelp
    ekpo~txz01
    ekpo~matnr
    ekpo~werks
    ekpo~menge
    ekpo~meins
    ekpo~netpr
    ekpo~netwr
    INTO TABLE t_itab1 FROM
    ekko INNER JOIN ekpo ON ekkoebeln = ekpoebeln
    WHERE ekko~ebeln IN s_ebeln AND
    ekko~bukrs IN s_bukrs AND
    ekko~lifnr IN s_lifnr AND
    ekko~ekorg IN s_ekorg AND
    ekko~ekgrp IN s_ekgrp AND
    ekpo~matnr IN s_matnr.
    The difference between an INNER JOIN and an OUTER JOIN is the following. If a query on an INNER JOIN of VBAK (outer table) and VBAP (inner table) finds a record in VBAK but no matching records in VBAP, then no data is retrieved from the database because the inner table is empty. If you still want to keep VBAK rows for which there are no matching VBAP rows, you need to use the OUTER JOIN construct available in ABAP/4 Open SQL in 4.x..
    Hi
    Syntax
    ... [(] {dbtab_left [AS tabalias_left]} | join
    {[INNER] JOIN}|{LEFT [OUTER] JOIN}
    {dbtab_right [AS tabalias_right] ON join_cond} [)] ... .
    Effect
    The join syntax represents a recursively nestable join expression. A join expression consists of a left-hand and a right- hand side, which are joined either by means of [INNER] JOIN or LEFT [OUTER] JOIN . Depending on the type of join, a join expression can be either an inner ( INNER) or an outer (LEFT OUTER) join. Every join expression can be enclosed in round brackets. If a join expression is used, the SELECT command circumvents SAP buffering.
    On the left-hand side, either a single database table, a view dbtab_left, or a join expression join can be specified. On the right-hand side, a single database table or a view dbtab_right as well as join conditions join_cond can be specified after ON. In this way, a maximum of 24 join expressions that join 25 database tables or views with each other can be specified after FROM.
    AS can be used to specify an alternative table name tabalias for each of the specified database table names or for every view. A database table or a view can occur multiple times within a join expression and, in this case, have various alternative names.
    The syntax of the join conditions join_cond is the same as that of the sql_cond conditions after the addition WHERE, with the following differences:
    At least one comparison must be specified after ON.
    Individual comparisons may be joined using AND only.
    All comparisons must contain a column in the database table or the view dbtab_right on the right-hand side as an operand.
    The following language elements may not be used: BETWEEN, LIKE, IN.
    No sub-queries may be used.
    For outer joins, only equality comparisons (=, EQ) are possible.
    If an outer join occurs after FROM, the join condition of every join expression must contain at least one comparison between columns on the left-hand and the right-hand side.
    In outer joins, all comparisons that contain columns as operands in the database table or the view dbtab_right on the right-hand side must be specified in the corresponding join condition. In the WHERE condition of the same SELECT command, these columns are not allowed as operands.
    Resulting set for inner join
    The inner join joins the columns of every selected line on the left- hand side with the columns of all lines on the right-hand side that jointly fulfil the join_cond condition. A line in the resulting set is created for every such line on the right-hand side. The content of the column on the left-hand side may be duplicated in this case. If none of the lines on the right-hand side fulfils the join_cond condition, no line is created in the resulting set.
    Resulting set for outer join
    The outer join basically creates the same resulting set as the inner join, with the difference that at least one line is created in the resulting set for every selected line on the left-hand side, even if no line on the right-hand side fulfils the join_cond condition. The columns on the right-hand side that do not fulfil the join_cond condition are filled with null values.
    Example
    Join the columns carrname, connid, fldate of the database tables scarr, spfli and sflight by means of two inner joins. A list is created of the flights from p_cityfr to p_cityto. Alternative names are used for every table.
    PARAMETERS: p_cityfr TYPE spfli-cityfrom,
    p_cityto TYPE spfli-cityto.
    DATA: BEGIN OF wa,
    fldate TYPE sflight-fldate,
    carrname TYPE scarr-carrname,
    connid TYPE spfli-connid,
    END OF wa.
    DATA itab LIKE SORTED TABLE OF wa
    WITH UNIQUE KEY fldate carrname connid.
    SELECT ccarrname pconnid f~fldate
    INTO CORRESPONDING FIELDS OF TABLE itab
    FROM ( ( scarr AS c
    INNER JOIN spfli AS p ON pcarrid = ccarrid
    AND p~cityfrom = p_cityfr
    AND p~cityto = p_cityto )
    INNER JOIN sflight AS f ON fcarrid = pcarrid
    AND fconnid = pconnid ).
    LOOP AT itab INTO wa.
    WRITE: / wa-fldate, wa-carrname, wa-connid.
    ENDLOOP.
    Example
    Join the columns carrid, carrname and connid of the database tables scarr and spfli using an outer join. The column connid is set to the null value for all flights that do not fly from p_cityfr. This null value is then converted to the appropriate initial value when it is transferred to the assigned data object. The LOOP returns all airlines that do not fly from p_cityfr.
    PARAMETERS p_cityfr TYPE spfli-cityfrom.
    DATA: BEGIN OF wa,
    carrid TYPE scarr-carrid,
    carrname TYPE scarr-carrname,
    connid TYPE spfli-connid,
    END OF wa,
    itab LIKE SORTED TABLE OF wa
    WITH NON-UNIQUE KEY carrid.
    SELECT scarrid scarrname p~connid
    INTO CORRESPONDING FIELDS OF TABLE itab
    FROM scarr AS s
    LEFT OUTER JOIN spfli AS p ON scarrid = pcarrid
    AND p~cityfrom = p_cityfr.
    LOOP AT itab INTO wa.
    IF wa-connid = '0000'.
    WRITE: / wa-carrid, wa-carrname.
    ENDIF.
    ENDLOOP.

  • Join fact table with higher dimension level

    how do i join fact tables with higher dimension levels with discoverer?
    fact with detail at level C
    measure X
    dimension with
    D->C->B->A
    E->C
    level
    A B C
    1------1------1
    2------2------1
    3------2------1
    join between fact X and dimension level C
    X=3*C because of sum(X) in discoverer and 3xC in dimension
    is there a way to get correct values for X without creating a dimension like
    D->C
    E->

    another way of asking this is whether you can create a summary table in Discoverer at a higher level than a dimension's fundamental grain. In other words - the summary examples in the documentation all describe leaving out one or more of your dimensions... they are either left in or completely taken out. But, some of the most effective summarization occurs when you summarize daily data to a monthly level. Assuming that I have a sales table (at a daily level, and a key value sales_date), and a table date_dim (primary key sales_date), I would like to create a summary sales_month_summary where the sales are grouped on month_year (which is a field in the sales_date table).
    How is this done? I suspect that we can't use the date_dim table with the summary (due to the problems noted by the poster above). Do we have to create another table "month_dim"? Do we have to fold all of the desired date attributes (month, quarter, year) into the summary? Obviously we'd like to re-use all of the pertinent already existing date items (quarter, month, year, etc.), not recreate them over again, which would result in essentially two sets of items in the EUL. [One used for this month summary, and another used for the detail.]
    I searched the forum - someone asked this same question back in 2000 - there was no answer provided.
    The only other thought I have is to "snowflake" the date_dim into two tables and two folders, one at a date level, another at the month level. Then the detail tables can connect to date_dim (which is linked to month_dim), while the summary data can connect directly to month_dim.

Maybe you are looking for

  • How to enable excel downloading in ALV grid report.

    Hi all, How to enable excal downing in ALV grid report? Thanks in Advance. Siva Sankar.

  • FRM-92101:

    Hi I've got an error message while running form.it is.... FRM-92101:There was a failure in the Forms Server during startup. This could happen due to invalid configuration. Please look into the web-server log file for details. What may be the fault an

  • Script to merge 2 Indesign files on alternating pages

    Hello I have created a data merge document for a book I am writing (Luckily I already had everything in Excel) . I created a template with the style headings and graphics frames positioned and sized exactly where I wanted them.My master page had repe

  • How can i set the network time on my appleTV?

    Since the last update I have been unable to use my Appletv.  It says it can't get the network time.  I've restarted my router and unplugged the appleTV numerous times.  I've heard others have this problem too.  What is the solution?

  • Cannot copy to clipboard on Ctrl+C or Event.COPY because of Error #2191

    There is a problem in Flash Player on Linux with writing to clipboard by pressing Ctrl+C or any other keyboard key. According to the security policy of Flash Player writing to clipboard is allowed only as the result of user interaction. The keyboard