Pergunta

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)
)

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

output e.g.

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

As my first post on stackoverflow.com ( even if i followed it in the past) i want to thank you for any reply to my question and thank you all for create and help this beautiful community!

Best regards

Francesco

Foi útil?

Solução

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;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top