How to join a column of same values to another different table in SQL?

原问题:

I have this table structure for names_table:

NameAgeGender
Someone125Male
Someone225Female
names_table

Another table names_with_company has this structure:

CompanyIDNameAgeGender
names_with_company

Now, I want to copy the data from names_table by adding a single value to column of CompanyID.

Expected result:

CompanyIDNameAgeGender
1234Someone125Male
1234Someone225Female
names_with_company

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

(0)
上一篇 2022-02-21 20:28
下一篇 2022-02-21 21:19

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注