Monday, March 12, 2012

Joining 2 tables...

Hi. I'm new to SQL, and need to join 2 tables... any hints?

table1:
id (int)
title(varchar(50))
body(text)

table2:
id (int)
title(varchar(50))
body(text)

somehow need to get the id, which table the record is from, and the title and body... so if the tables had the information:

table1:
id title body
1 "first title" "first body"
2 "second title" "second body"
3 "third title" "third body"

table2:
id title body
1 "first title" "first body"
2 "second title" "second body"
3 "third title" "third body"

I would like to get...

id table title body
3 1 "third title" "third body"
3 2 "third title" "third body"
2 1 "second title" "second body"
2 2 "second title" "second body"
1 1 "first title" "first body"
1 2 "first title" "first body"

Does anyone know how to get this? I am fairly flexible if i need to change things...

cheers, eh!

SELECT 'A', Id, Title, Body FROM TABLE1
UNION
SELECT 'B', Id, Title, Body FROM TABLE2
ORDER BY Id DESC, 1 ASC

No comments:

Post a Comment