Search code examples
sqljoinstored-proceduresfirebirdfirebird2.5

Mix records of two different tables


I'm looking for a way to solve my SQL problem.

I have 2 tables in Firebird 2.5 ( T1 and T2 ) like these:

T1 (
 T1_ID INTEGER,
 T1_DAY DATE,
 T1_NAME VARCHAR(200)
)

T2 (
 T2_ID INTEGER,
 T2_DAY DATE,
 T2_NAME VARCHAR(200)
)

I need a query that mixes records of those tables and sort them in ascending date order. I don't care if a join query increases the number of fields or the date field is not the same as result or stored procedures are needed.

Example output

T1_ID   T1_DAY   T1_NAME T2_ID   T2_DAY   T2_NAME
---------------------------------------------------
  1   01/02/2011  BOB     NULL    NULL     NULL
  2   27/02/2011  SAM     NULL    NULL     NULL
 NULL    NULL     NULL     8   15/03/2011  PETER
 NULL    NULL     NULL     10  21/03/2011  JOHN
  6   17/04/2011  AMY     NULL    NULL     NULL

or (better output)

 ID       DAY     NAME
-------------------------
  1   01/02/2011  BOB
  2   27/02/2011  SAM
  8   15/03/2011  PETER
  10  21/03/2011  JOHN
  6   17/04/2011  AMY

Solution

  • You want the UNION operator:

    SELECT
       T1.T1_ID ID,
       T1.T1_DAY DAY,
       T1.T1_NAME NAME
    FROM
       T1
    
    UNION
    SELECT
        T2.T2_ID,
        T2.T2_DAY
        T2.T2_NAME
    FROM
        T2
    ;
    

    You can make the individual selects have any additional features you like. The only restriction is that all of the columns in both of the select lists are in the same order and have the same type (they are "union compatible"). The resulting rows will have column headings like the first select.

    edit: To control the ordering of a union, you'll have to do the union in a subselect and the ordering in the outer query.

    SELECT u.ID, u.DAY, u.NAME
    FROM (
        SELECT T1.T1_ID ID, T1.T1_DAY DAY, T1.T1_NAME NAME
        FROM T1
    
        UNION
        SELECT T2.T2_ID, T2.T2_DAY T2.T2_NAME
        FROM T2
    ) u
    ORDER BY u.NAME;