我的问题涉及将数据从一个 cdv 文件复制到多个表中。我的 table 是
CREATE TABLE IF NOT EXISTS apt_info
(
house_number varchar(10) NOT NULL,
block varchar(3) NOT NULL,
owner_id int,
KEY owner_id (owner_id),
CONSTRAINT apt_owner FOREIGN KEY (owner_id) REFERENCES owner_info(owner_id),
tenant_id INT,
KEY tenant_id (tenant_id),
CONSTRAINT apt_tenant FOREIGN KEY (tenant_id) REFERENCES tenant_info(tenant_id),
CONSTRAINT apt_id PRIMARY KEY (block, house_number)
other columns storing different apt related values
);
CREATE TABLE IF NOT EXISTS owner_info
(
owner_id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
firstname varchar(80),
lastname varchar(80),
other column storing different owner related values
);
我有一个 CSV 文件,其中每行包含公寓详细信息,包括业主姓名。由于我想将所有者信息存储在不同的表中并且同一所有者可能有多个公寓,因此我创建了一个临时表
Title,FirstName,Last Name,block,house_number,Sq. Foot Mr,Debraj,Gupta,A,101,1709 ,Laxman, ,A,102,1463 ,Laxman, ,A,103,1418 Mr,T A,Padmanabhan,A,104,1821
I created a temp_owner_info
table with fields for each column and used LOAD DATA
to insert these records. Then I populated owner_info
table with
INSERT INTO owner_info (title, firstname, lastname)
SELECT DISTINCT title, firstname, lastname
FROM temp_owner_info;
现在我想用 temp_owner_info
中的 block、house_number、sq_ft 详细信息和 owner_info
表中的 owner_id 填充 apt_info
表
我该怎么做?我想要的owner_id可以通过比较名字和姓氏的值得到。我是 SQL 新手,无法编写比较多个表的值所需的 select 语句。
我认为将 owner_id 列添加到 temp_owner_info 表并在使用该信息填充 apt_info 之前从 owner_info 获取自动生成的值更容易 但是下面的查询以错误消息结束
更新 temp_owner_info tmp 设置 owner_id = o.owner_id 来自 owner_info 作为 o 在哪里 tmp.firstname = o.firstname 和 tmp.lastname = o.lastname;
错误消息:错误代码 1064,SQL 状态 42000:您的 SQL 语法有误;查看与您的 MySQL 服务器版本相对应的手册,了解在 'from owner_info as o 附近使用的正确语法 在哪里 tmp.firstname = o.firstname 和 tmp.lastname = o.las' 在第 3 行 第 1 行,第 1 列
最佳答案
试试这个:
Insert into apt_info (block, house_number, sq_ft, owner_id)
SELECT toi.block, toi.house_number, toi.sq_ft,
(select oi.owner_id from owner_info oi
where oi.firstname = toi.firstname
and oi.lastname = toi.lastname) owner_id
from temp_owner_info toi
关于mysql - 根据使用其他表中的数据而不是需要插入的数据的查询将数据插入到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21528835/