tags:

views:

31

answers:

2

Hi there. I'm looking for a query to select rows from two different tables, keeping the column names the same (I did find one result here for selecting from two different tables, but it merged the column names to have an easier query). I need to keep the original column names, but have two different tables existing within the new, larger table. There are no overlapping columns between the two tables.

A picture, to visualise:

alt text

So, how can I do this? I know the query will probably be quite convoluted, but anything half-decent is probably going to be better than my current attempt:

SELECT t1.* , t2.*
FROM table1 t1 RIGHT OUTER JOIN table2 t2
ON r.someColumn1 = rc.someColumn2
UNION
SELECT t1.* , t2.*
FROM table1 t1 LEFT OUTER JOIN table2 t2
ON r.someColumn1 = rc.someColumn2

This does work, but only as long as there are no cases where someColumn1 = someColumn2 - which can happen quite easily, of course.

Any help is appreciated, and I apologise for what is probably a very silly question to which the smart answer is "don't do it, you fool!".

+2  A: 

Edit: my first answer was wrong:

select * from Events
  left join GroupList on ID=null
union 
select Events.*,GroupList.* from GroupList 
  left join Events on GID=null

In the above GID and ID are keyfields in the tables.

Richard Harrison
That'll give you a cartesian join, which will give you each row in table1 matched up with each row in table2.
Adam Ruth
Indeed, Adam is right. I'm looking for two unique tables as in my picture, not a cartesian. Sorry.
Stephen
You're right - I didn't understand. Now I've editted it it's almost the same the answer given by @Adam, so he gets my +1.
Richard Harrison
Very gentlemanly of you. You get my +1.
Adam Ruth
+5  A: 

You can set your join criterion to never match:

SELECT t1.* , t2.*
FROM table1 t1 RIGHT OUTER JOIN table2 t2
ON 1 = 0
UNION
SELECT t1.* , t2.*
FROM table1 t1 LEFT OUTER JOIN table2 t2
ON 1 = 0

I don't have MySQL to test, but it works in SQL Server.

Adam Ruth
It works; I just tested it in MySQL.
Lèse majesté
Thanks, Lèse, it's standard SQL but I always like to double check.
Adam Ruth
I have tested it with `ON FALSE`. It works.
Michas
Thanks Adam, this works fine for me. You get my upvote for now, and if nobody comes storming in to suddenly bestow new knowledge upon this poor unlightened soul in the next few hours, you can have the answer tick too! Michas, thanks for the ON FALSE.
Stephen
4 hours seems long enough. Thanks again, Adam.
Stephen
ON FALSE, excellent. Too bad SQL Server doesn't have a boolean data type, that's cleaner.
Adam Ruth