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

时间:2018-06-15 12:23:08

标签: mysql lua

我的文本文件的值如下:

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”col不存在则插入表中

我可以逐行读取带有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读取文本文件并插入?

2 个答案:

答案 0 :(得分:3)

您的代码违反了主键约束:它为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)

答案 1 :(得分:0)

使用字段创建唯一索引   ALTER TABLE Person ADD UNIQUE Code_DateCodeDate);

然后运行ignor查询它将不允许重复数据

INSIGN IGNORE INTO Person(代码,日期,进,出) 价值观(9001,20180501,' 08:30',' 12:30')