开发者

How to select two seperate non-overlapping tables in MySQL

I'm looking for a query to select r开发者_如何学Pythonows 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:

How to select two seperate non-overlapping tables in MySQL

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!".


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜