原问题:
I have this table structure for names_table:
Name | Age | Gender |
Someone1 | 25 | Male |
Someone2 | 25 | Female |
Another table names_with_company has this structure:
CompanyID | Name | Age | Gender |
Now, I want to copy the data from names_table by adding a single value to column of CompanyID.
Expected result:
CompanyID | Name | Age | Gender |
1234 | Someone1 | 25 | Male |
1234 | Someone2 | 25 | Female |
I am quite confused what should I include.
INSERT INTO names_with_company
'1234',SELECT * FROM names_table
or
INSERT INTO names_with_company
SELECT * FROM (
'1234'
UNION
SELECT * FROM names_table
)
These two doesn’t work
I know these two tables are two different structures, but is there any way to have a static value in column and rest of the data from another table?
Also, can you please not suggest creating another table and joining them? I prefer it to be done using the above code lines, but with a working logic.
采纳答案:
Get into the habbit of always specifying the column names:
INSERT INTO names_with_company (CompanyID, Name, Age, Gender)
SELECT 1234, Name, Age, Gender
FROM names_table;
As you can see, you can provide “literal” values for any column.
问题解析:
该问题主要是想将names_table中的数据插入到names_with_company,并且设置companyid为常量值1234,在数据库中有多种插入数据的方式,比如:
insert into table_1 (col1,col2,col3) values (value1,value2,value3);
也可以将某一个表的查询结果直接插入到表,如:
insert into table_1(col1,col2,col3) select col1,col2,col3 from table_2;
如果我们希望每一行都显示一个固定常量,则可以将常量值放入查询语句中,如:
select '常量值',col1,col2,col3 from table_2;
这个问题主要是不知道如何将常量值放入查询结果中。
本文根据StackOverflow翻译而来,不代表烟海拾贝立场,如若转载,请注明出处:https://somirror.com/560.html