問題描述
我檢查了這個站點的代碼來堆疊兩個表(將一個表的結果放在另一個表的結果下方),其中列名不同.我知道當名稱相同時 UNION ALL 有效..而且我知道 UNION ALL 對一個表中缺少的列名進行分配時,當一個表比另一個表具有更多信息時會起作用..但是如果該列會怎樣名字不一樣?就像如果在一張表中的列名稱是 CHP 而在另一張表中它是CHILD HEALTH PLUS"并且我需要將這兩列堆疊在一起會怎樣?
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?
推薦答案
只要列的數據類型相同,就可以使用 UNION.列名是否不同并不重要.
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
這篇關于用不同的列名堆疊兩個 sql 表 (2008)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!