简体   繁体   English

在SQL中执行Insert into语句,导致其他列为null

[英]Executing Insert into statement in SQL resulting in nulls for other columns

i am trying to use an insert into a column where the data for other columns already exists, but the data is not populating adjacent to the other columns, instead data is inserted after all the data in the table. 我试图在其中已存在其他列的数据的列中使用插入,但数据不会填充到其他列的附近,而是在表中的所有数据之后插入数据。 For example: 例如:

select * from tab1;       
ID NAme Last_name          
1  King                     
2  Queen                   
3  Rook 

select * from tab2;
Id LastName_Name
1  Abc 
2  def
3  xyz

SQL : Insert into tab1 (Last_name)
select tab2.LastName_Name from tab1,tab2, where tab1.Id=tab2.Id

Output:
Id Name Last_Name
1  King   NULL
2  Queen  NULL
3  Rook   NULL
4  NULL   Abc
5  NULL   def
6  NULL   xyz

But I want the data as below: 但我想要的数据如下:

Id Name Last_Name
1  King   Abc
2  Queen  def
3  Rook   xyz

Any work around for this? 有什么解决方法吗? thanks in advance :) 提前致谢 :)

Step2: 第2步:

select * from tab1; 从tab1中选择*;

ID Name Id2 ID名称Id2

1 King NA 1 King NA

2 Queen NA 2女王NA

3 Rook NA 3 Rook NA

select * from tab2; 从tab2中选择*;

ID 

1  

2  

3  

4

5

6

I want the Output data as below: 我想要输出数据如下:

The ID data in tab2 should populate in tab1 column (ID2) which are matching with TAB1.ID column values as below: tab2中的ID数据应填充在tab1列(ID2)中,该列与TAB1.ID列值匹配,如下所示:

Id Name ID2
1  King   1
2  Queen  2
3  Rook   3

Can you please provide any query for this? 你能否提供任何疑问?

So you are wanting to UPDATE the rows in tab1 with the corresponding last names from tab2? 所以你想要更新tab1中的行与tab2中相应的姓氏?

In which case, use an UPDATE statement instead of an INSERT: 在这种情况下,使用UPDATE语句而不是INSERT:

UPDATE tab1
SET tab1.Last_name = tab2.LastName_Name
FROM tab1
    JOIN tab2 ON tab1.Id = tab2.Id

You don't need an INSERT you need an UPDATE statement: 您不需要INSERT需要UPDATE语句:

UPDATE tab1 SET tab1.Last_name = tab2.LastName_Name
FROM tab1 INNER JOIN tab2 ON tab1.Id = tab2.Id

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

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