mysql - 使用 Perl 将多个逗号分隔值添加到 MySQL 行

标签 mysql perl

我有这段代码:

if (my $ref = $sth->fetchrow_hashref()) {
    my $related_id = $ref->{'products_id'};
    my $sql = "REPLACE INTO products_xsell (products_id, xsell_id) 
        VALUES (".$product_id.", ".$related_id.")";
    $dbh->do($sql);
    $c_processed++;
}

目前,数据如下:

product_id   product_id
9999            22
8888            21
9999            66
7777            77
9999            88

我想像这样存储数据:

product_id   product_id
9999            22,66,88
8888            21
7777            77

我一直在阅读有关使用 JOIN 的内容,但似乎不知道如何操作。我继承了这段代码,它没有使用准备好的语句和占位符。 我希望一旦掌握了 Perl 的窍门就能解决这个问题。

最佳答案

我会警告不要在 Perl 中进行“数据修改”,当您拥有一个几乎不变的数据库时,最好在“数据库端”进行此操作 - 毕竟,这就是数据库的用途

但是要回答您的一般问题 - 您需要的是哈希:

#!/usr/bin/env perl 
use strict;
use warnings;

#our hash
my %combined;

#header row - grabs first line and prints it. 
print scalar <DATA>; 

#iterates line by line
while ( <DATA> ) {
   #removes linefeeds
   chomp;
   #splits on whitespace. 
   my ($key, $value ) = split;
   #stores in combined hash of arrays.  
   push ( @{$combined{$key}}, $value ); 
}

#cycle through our hash, extracting each key and 
#merge the array into a string, comma delimited. 
foreach my $prod ( sort keys %combined ) { 
    print join ("\t", $prod, join ( ",", @{$combined{$prod}} ) ),"\n";
}


__DATA__
product_id   product_id
9999            22
8888            21
9999            66
7777            77
9999            88

鉴于您的数据库查询返回哈希引用,那么您不需要如上所述的“拆分”部分 - 因为您实际上已经完成了它。该代码旨在说明该技术(尤其是因为我没有您的数据库,所以这样我们就得到了一个可运行的示例)。

关于mysql - 使用 Perl 将多个逗号分隔值添加到 MySQL 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32939892/

相关文章:

php - 一般错误 : 1366 Incorrect integer value ( QUERY EXEPTION )

git - 无法应用 git 属性过滤器

perl - 如何从 Perl 程序返回一个值给 Korn-shell 脚本?

mysql - 在mysql批处理中运行多个sql文件

mysql - 如何处理涉及多个表的 SQL 查询

mysql - 使用基本连接进行多个值的 sql 查询

php - 从 Zend 中的 2 个表获取结果

Perl 间歇性地无法连接到 iis 7.5(Windows Server 2012 上的 cygwin)

perl - 如何测试嵌入在 bash 脚本中的 perl 命令是否返回 true?

perl - 如何捕获还需要用户从终端输入的命令的所有输出?