如何使MYSQL列等于选择查询

时间:2016-06-12 09:56:19

标签: mysql

抱歉,如果这是一个基本问题,但我是mysql的新手,我有两个表,其中一个是CustomerID vs地址,而第二个是CustomerID vs transaction。

我想在第二个表中为地址添加列,并使此列始终使用客户ID从第一个表中选择地址并写入。所以我最后有一个表有客户ID,交易和地址。我读到了存储的函数和过程,但我无法弄清楚如何在我的情况下应用它。 (我使用的是phpmyadmin)

编辑(我需要动态,每次向表2添加新行时,它会在表1中查找客户ID并获取其地址并将其写入表2中)

2 个答案:

答案 0 :(得分:0)

table_addr (CustomerID,address)
table_trans(CustomerID,transaction)

所以你需要SQL

select * from table_trans join table_addr on table_trans.CustomerID = table_addr.CustomerID;
是吗?

答案 1 :(得分:0)

首先,您应该在第二个表格中添加一列address,我将其视为table2,如:

alter table `table2` add `address` varchar(100) default '';
-- this column's type should be as same as `address` in first table which I assume it as table1

其次,使用address的地址更新table2中的所有table1

update table2 inner join table1 on table2.customerId = table1.customerId
set table2.address = table1.address