gpt4 book ai didi

Mysql 查询 - 从 CSV 条件插入到表和 CSV 之间的比较

转载 作者:行者123 更新时间:2023-11-29 10:17:31 28 4
gpt4 key购买 nike

当涉及到 SQL 查询时,我是一个新手,不知道如何解决这个问题:我有一个包含 5 列的 CSV 文件,其中 2 列是 Value1 和 Value2,我需要运行现有的 sql 表(出于这个问题的目的,我将其称为“目标表”)并迭代目标中的所有行表检查其 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”运行更新,但我可能是错的。

任何帮助将不胜感激,谢谢!

最佳答案

从理论上讲,我认为这应该适合您。

--第 1 部分:清除/创建临时表并将 CSV 加载到 SQL 中。感谢 mr_eclair 描述此过程 here

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
)

--第 2 部分:设置唯一 key ;按照@Yuri_Lachin 的建议

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

--第 3 部分:添加行并将值从临时表更新到永久表。归功于 MySQL 5.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);

关于Mysql 查询 - 从 CSV 条件插入到表和 CSV 之间的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49897767/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com