使用来自 csv 的 MySQL 处理列的任何方法?
Any Way to Process Columns using MySQL from csv?
我有一个 csv 文件,其中包含 ipv4 网络和掩码,格式如下:41.74.160.0/20
我想将其分为网络长和广播长,以便我可以检查此范围内的其他长,以便与另一个 table 进行匹配。到目前为止,我只是将它存储为一个字符串,因为 INET_ATON 接受一个字符串,但我最近发现它不支持掩码。我也一直在使用 LOAD DATA INFILE 作为轻松获取 table.
中所有数据的解决方案
但是,在这个新解决方案中,我的 table 中的列显然与我的数据中的列不匹配。有什么方法可以通过处理 MySql 中的 csv 文件中的列来加载数据?如果没有,在 PHP 中是否有简单的方法?
MySQL 可以预处理 CSV 文件的输入,如果我理解你的要求,这是一个简单的字符串操作问题。 SUBSTRING_INDEX()
可以根据/
作为分隔符提取IP地址和掩码。
从这个开始 table:
CREATE TABLE `ipAddresses` (
`id` int NOT NULL AUTO_INCREMENT,
`ipComplete` varchar(45) NOT NULL,
`ipAddress` varchar(45) NOT NULL,
`ipMask` varchar(45) NOT NULL,
`fieldName` varchar(45) NOT NULL,
`inetNumeric` bigint NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB;
而这个 CSV 输入:
"A field 1",41.74.160.0/20
"A field 2",41.74.160.1/20
"A field 3",41.74.160.2/20
"A field 4",41.74.160.3/20
这个查询:
load data infile '/sqlfiles/ips.csv' into table ipAddresses
columns terminated by ','
enclosed by '"'
lines terminated by '\n'
(fieldName, @ip)
set ipComplete = @ip,
ipAddress = substring_index(@ip,'/',1),
ipMask = substring_index(@ip,'/',-1),
inetNumeric = inet_aton(substring_index(@ip,'/',1));
给出这个结果:
# id ipComplete ipAddress ipMask fieldName inetNumeric
29 41.74.160.0/20 41.74.160.0 20 A field 1 692756480
30 41.74.160.1/20 41.74.160.1 20 A field 2 692756481
31 41.74.160.2/20 41.74.160.2 20 A field 3 692756482
32 41.74.160.3/20 41.74.160.3 20 A field 4 692756483
我有一个 csv 文件,其中包含 ipv4 网络和掩码,格式如下:41.74.160.0/20
我想将其分为网络长和广播长,以便我可以检查此范围内的其他长,以便与另一个 table 进行匹配。到目前为止,我只是将它存储为一个字符串,因为 INET_ATON 接受一个字符串,但我最近发现它不支持掩码。我也一直在使用 LOAD DATA INFILE 作为轻松获取 table.
中所有数据的解决方案但是,在这个新解决方案中,我的 table 中的列显然与我的数据中的列不匹配。有什么方法可以通过处理 MySql 中的 csv 文件中的列来加载数据?如果没有,在 PHP 中是否有简单的方法?
MySQL 可以预处理 CSV 文件的输入,如果我理解你的要求,这是一个简单的字符串操作问题。 SUBSTRING_INDEX()
可以根据/
作为分隔符提取IP地址和掩码。
从这个开始 table:
CREATE TABLE `ipAddresses` (
`id` int NOT NULL AUTO_INCREMENT,
`ipComplete` varchar(45) NOT NULL,
`ipAddress` varchar(45) NOT NULL,
`ipMask` varchar(45) NOT NULL,
`fieldName` varchar(45) NOT NULL,
`inetNumeric` bigint NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB;
而这个 CSV 输入:
"A field 1",41.74.160.0/20
"A field 2",41.74.160.1/20
"A field 3",41.74.160.2/20
"A field 4",41.74.160.3/20
这个查询:
load data infile '/sqlfiles/ips.csv' into table ipAddresses
columns terminated by ','
enclosed by '"'
lines terminated by '\n'
(fieldName, @ip)
set ipComplete = @ip,
ipAddress = substring_index(@ip,'/',1),
ipMask = substring_index(@ip,'/',-1),
inetNumeric = inet_aton(substring_index(@ip,'/',1));
给出这个结果:
# id ipComplete ipAddress ipMask fieldName inetNumeric
29 41.74.160.0/20 41.74.160.0 20 A field 1 692756480
30 41.74.160.1/20 41.74.160.1 20 A field 2 692756481
31 41.74.160.2/20 41.74.160.2 20 A field 3 692756482
32 41.74.160.3/20 41.74.160.3 20 A field 4 692756483