I checked this site for code to stack two tables (put the results from one table beneath the results from another) where the column names are different. I know that UNION ALL works when the names are the same.. and I KNOW THAT UNION ALL with an assignment for the column names that are missing from one table works when one table has more info than the other.. but what if the column names are different? like what if in one table the column name is CHP and in another it is "CHILD HEALTH PLUS" and I need those two columns to be stacked on top of one another?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
A UNION can be used as long as the datatypes of the columns are the same. It doesn't matter if the column names are different.
SELECT column1
FROM Table1
UNION
SELECT column1
FROM Table2
If you want to know which table the records are coming from, then you can add another field that will distinguish the rows:
SELECT column1, 'Table1' as TableName
FROM Table1
UNION
SELECT column1, 'Table2' as TableName
FROM Table2
回答2:
what sql language? mysql/sql server?
mysql doesn't require that the column names be the same, but you could always use 'AS' to match up the column names eg.
select column1 AS col1, column2 AS col2...
EDIT: i just spotted the '2008' in the post title - is that sql server 2008? in any case, sql server doesn't seem to care re. column names either.