简体   繁体   English

想要通过SQL在MS Access查询中添加新列

[英]Want to add a New column in MS Access query via SQL

I have 3 tables they all have the same column header Name, Number I have joined them using the union command as shown below: 我有3个表,它们都具有相同的列标题Name,Number,我使用union命令将它们加入其中,如下所示:

SELECT Name, Number
FROM table1
Union all
select name, number
from table2
UNION ALL select name, number
from table3;

Every thing is right up till here. 一切都到这里为止。 Now I want to add a new column which should contain the information about from which table this data have been taken. 现在,我想添加一个新列,其中应包含有关从哪个表获取了此数据的信息。 I am using the alter table command but it gives error. 我正在使用alter table命令,但它给出了错误。

Kindly help me. 请帮助我。 I am working on MS access 2007. 我正在使用MS Access 2007。

Just add it in as a column in each subquery: 只需在每个子查询中将其添加为列即可:

SELECT Name, Number, 'table1' as which
FROM table1
Union all
select name, number, 'table2' as which
from table2
UNION ALL
select name, number, 'table3' as which
from table3;

ALTER TABLE only works on actual tables, not query results. ALTER TABLE仅适用于实际表,不适用于查询结果。

You simply need to add the information as a pseudo-column to your current query: 您只需要将信息作为伪列添加到当前查询中:

SELECT 
  Name, Number, 'Table1' as TableName
FROM 
  table1
Union all
select 
  name, number, 'Table2'
from 
  table2
UNION ALL 
select 
  name, number, 'Table3'
from table3;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM