如何读取文本文件并插入mysql tabel(如果不存在)

iq0todco  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(406)

我有一个文本文件,其值如下:

9001,20180501,08:30,12:30;
9002,20180501,08:30,14:00;
9003,20180501,08:30,12:25;
9004,20180501,08:15,12:30;
9001,20180502,08:11,12:32;
9002,20180502,08:24,12:34;
9003,20180502,07:51,13:52;
9004,20180502,08:30,12:30;
9001,20180503,08:30,12:30;
9002,20180503,08:30,12:30;
9003,20180503,08:30,12:30;
9004,20180503,08:30,12:30;

我有一个名为“person”的表,其值如下:

id (INT, PK, A_I)      |   Code   |    Date   |   In   |   Out   |
1                          9001      20180501    08:30    12:30
2                          9002      20180501    08:30    14:00

现在我想逐行读取文本文件,并在“code”和“date”列不存在时插入到表中
我可以将带有lua的文本文件逐行读入变量并使用以下代码:

INSERT INTO Person (id, Code, Date, In, Out) 
VALUES (null, 9001, 20180501, '08:30', '12:30') 
WHERE NOT EXIST (SELECT Code,Date FROM Person WHERE Code=9001 AND Date=20180501)

但它不起作用!
你想用mysql读取文本文件并插入吗?

laximzn5

laximzn51#

您的代码违反了主键约束:它提供了 NULL 的值 id .
id 是自动递增,您根本不必指定它:

INSERT INTO Person (Code, Date, In, Out) 
VALUES (9001, 20180501, '08:30', '12:30') 
WHERE NOT EXISTS (SELECT Code,Date FROM Person WHERE Code=9001 AND Date=20180501)

编辑:上面的语法对于mysql来说似乎不正确。您可以改为尝试此查询:

INSERT INTO Person (Code, Date, In, Out) 
SELECT Code, Date, In, Out
FROM 
(
   SELECT 9001 AS Code, 20180501 AS Date , '08:30' AS In, '12:30' AS Out
) as t
WHERE NOT EXISTS (SELECT Code,Date FROM Person WHERE Code=9001 AND Date=20180501)
j2cgzkjk

j2cgzkjk2#

使用字段创建唯一索引
然后运行inset ignore query它将不允许重复数据
alter table person add unique\索引'( Code , Date , In , Out )
在person(code,date,in,out)值中插入ignore(9001,20180501,'08:30','12:30')

相关问题