0

我有两个表,如 A 和 B。表 A 具有列名称。具有列公司名称的表 B。

这是我的代码:

$query1 = "SELECT Name FROM A"; 
$query2 = "SELECT Company Name FROM B"; 

$statement1 = $connection->prepare($query1);    
$statement2 = $connection->prepare($query2);

$statement1->execute();
$statement2>execute();

while ( ($name) = $statement->fetchrow_array) {
    push (@Name, $name);    
} 
while ( ($companyname) = $statement->fetchrow_array) {
    push (@companyName, $companyname);  
}

open (FH, ">>Output.csv") or die "$!";

我需要像这样在csv文件中写入数据

Name   CompanyName

xxx     yyyy

xxx     yyyy

xxx     yyyy

xxx     yyyy

xxx     yyyy
4

1 回答 1

1

您可以JOIN在 SQL 查询中使用 a 来执行此操作。你不需要做两个SELECT陈述。

'SELECT a.Name, b.CompanyName FROM A a JOIN B b ON a.MailId = b.MailId'

这是一个完整的例子:

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

my $dbh = DBI->connect("put:dsn:here");
my $sth = $dbh->prepare('SELECT a.Name, b.CompanyName FROM A a JOIN B b ON a.MailId = b.MailId');

open my $fh, '>>', 'Output.csv' or die "Could not open file Output.csv: $!";
print $fh qq{Name\tCompanyName\n};

$sth->execute;
while (my $res = $sth->fetchrow_hashref) {
  print $fh qq{$res->{'Name'}\t$res->{'CompanyName'}\n};
}
close $fh;
于 2012-10-08T07:49:38.513 回答