mysql查询-insert from csv条件表与csv比较

kiayqfof  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(233)

对于sql查询,我是个新手,不知道如何处理:我有一个包含5列的csv文件,其中2列是value1和value2,我需要运行一个现有的sql表(出于这个问题的目的,我称之为“target table”),并遍历target table中的所有行,检查它们的value1列,如果value1内容等于csv中的内容,我需要将value2插入该行的value2列如果value1未包含在表中,请为其创建新行。
以防万一我不清楚,举个例子-
假设csv如下所示:

Name, Age, Location, Height, Weight
David, 12, Macedonia, 1.87, 96
Kim, 15, Denmark, 1.95, 67

我想检查一下现有的sql,只根据名称和权重进行操作—如果表中有名称david,则在其权重列中插入96,如果表中有名称kim,则在其权重列中插入67等等。。。如果表中只包含kim而不包含david,那么将创建david行。
我假设明智的方法是先填补表中不存在的“value1”的空白,然后对“value2”运行更新,但我可能错了。
任何帮助都将不胜感激,谢谢!

vktxenjb

vktxenjb1#

理论上,我认为这应该对你有用。
--第1部分:清除/创建临时表并将csv加载到sql中。感谢埃克莱尔先生在这里描述了这一过程

drop table #temp

create table #temp (
tName nvarchar(25),
tAge int, 
tLocation nvarchar(25),
tHeight float(3,2), -- alternatively, use cm instead of m and just use int(3)
tWeight int
)

BULK INSERT #temp
FROM 'C:\CSVData\updates.csv'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ',',  --CSV field delimiter
ROWTERMINATOR = '\n',   --Use to shift the control to next row
TABLOCK
)

--第二部分:设置唯一键;正如@yuri\u lachin所建议的

Alter table target
Add Unique (Name) -- Sets Name column as a Unique Key for the table target

--第3部分:从临时表向永久表添加行和更新值。MySQL5.7参考手册13.2.5.2

Insert into target(Name, Age, Location, Height, Weight)
Select tName, tAge, tLocation, tHeight, tWeight from #temp
On DUPLICATE KEY Update Weight = tWeight

我本来打算建议使用如下的merge语句,但看起来mysql没有处理这些问题。

Merge Into people
using #temp
on target.name = #temp.tname
when matched then Update
set target.weight = #temp.tweight
when not matched then 
Insert (target.name, target.age, target.location, target.height, target.weight)
values (#temp.tname, #temp.tage, #temp.tlocation, #temp.theight,  #temp.tweight);

相关问题