2015-10-05 46 views
0

我有这样的一段代码分隔值到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的窍门后将其解决。

+0

在尝试像这样更改数据之前,您可能需要确保熟悉该架构。你在这里的示例表看起来很像一个外键映射表(将表A中的项目映射到表B中的项目,反之亦然),如果这就是你想做的事情案件。 –

+2

你提出的是一个非常糟糕的方式来存储数据。除非你的老板拿着枪对着你的头,迫使你以这种方式格式化数据,我建议你重新考虑你的设计。您可以在本网站上提问,了解如何格式化数据以满足您的需求。 – 2015-10-05 07:09:21

回答

0

我会在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 

鉴于你的数据库的查询返回一个hashref,那么你并不需要“分裂”的一部分如上 - 你已经有效地完成了它。此代码旨在说明该技术(并非最不重要的原因是我没有您的数据库,因此我们通过这种方式获得了一个可运行的示例)。