[英]SQL query to copy column from one table to another table based off index value
I am trying to formulate a query that copies the contents of one column in a table to another table and match it up with the index values.我正在尝试制定一个查询,将表中一列的内容复制到另一个表并将其与索引值匹配。
Both tables are going to have the same index values.两个表都将具有相同的索引值。
Example:例子:
Table1表格1
+-----------------------------------+------------+
| index | val |
+-----------------------------------+------------+
| 11 | AA |
| 23 | AA |
| 34 | BB |
+-----------------------------------+------------+
Table2表2
+-----------------------------------+
| index |
+-----------------------------------+
| 34 |
| 11 |
| 23 |
+-----------------------------------+
After query is run, make table 2 reflect:查询运行后,使表 2 反映:
+-----------------------------------+------------+
| index | val |
+-----------------------------------+------------+
| 34 | BB |
| 11 | AA |
| 23 | AA |
+-----------------------------------+------------+
I would appreciate any help offered.我将不胜感激提供的任何帮助。 Thanks in advance.提前致谢。
I don't quite understand why you would like to do this, but it could look something like:我不太明白你为什么要这样做,但它可能看起来像:
Alter table BTABLE add val varchar(10);
update BTABLE bta set val = (select ata.val from ATABLE ata where ata.index = bta.index);
the only thing is, this way you would have 2 completely identical tables...唯一的问题是,这样你就会有 2 个完全相同的表......
The easiest way to do what you describe, is to drop Table2
and recreate it as a copy of Table1
:执行您所描述的操作的最简单方法是删除Table2
并将其重新创建为Table1
的副本:
DROP TABLE Table2;
CREATE TABLE Table2 AS
SELECT * FROM Table1;
See the demo .请参阅演示。
Results (for Table2
):结果(对于表Table2
):
> index | val
> ----: | :--
> 11 | AA
> 23 | AA
> 34 | BB
Like Irina Avram told you, Why do you want to copy a column that already exists in your database.就像 Irina Avram 告诉您的那样,您为什么要复制数据库中已存在的列。 You can use JOIN and a SELECT statement to get what you want, without adding more datas in your database.您可以使用 JOIN 和 SELECT 语句来获得所需的内容,而无需在数据库中添加更多数据。
SELECT Table2.index, Table1.val FROM Table2 JOIN Table1 ON Table2.index = Table1.index
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.