0

I'm having two tables like A and B. Table A having the Columns Name. Table B having the Columns Company Name.

This is my code:

$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 "$!";

I need to write the data in the csv file like this

Name   CompanyName

xxx     yyyy

xxx     yyyy

xxx     yyyy

xxx     yyyy

xxx     yyyy
3
  • You should always use strict and use warnings, and declare your variables with my. It's not clear what your question is. Is there an error message? Commented Oct 8, 2012 at 7:47
  • Okay hereafter i'll use strict and warning.I need to write the data into csv file. Commented Oct 8, 2012 at 7:49
  • Please post the files in question, or at least test files which replicate your environment. Its easier to answer when we have some data to play around. Commented Oct 8, 2012 at 8:02

1 Answer 1

1

You can do that with a JOIN in your SQL query. You don't need to do two SELECT statements.

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

Here's a complete example:

#!/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;
Sign up to request clarification or add additional context in comments.

2 Comments

I'm having two queries. First query result should be write in the one column. second query result should be write in the next column
!Stefan Edwards: are you sure? Are you certain the names and company names are listed in a consistent order? Usually you're not and you do a join to match them up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.