Perl查询并获取列名

时间:2014-06-08 16:05:46

标签: mysql perl

我需要进行查询,我将通过多个列查找特定的字符串,并且我需要知道哪个列(名称)包含我需要的值。

在下面的示例中,我需要一个查询,我可以询问哪个列包含值1000000000002101214并返回f1。 DB是MySQL,我需要在Perl中完成编程。

+---------------------+---------------------+---------------------+
| f1                  | f2                  | f3                  |
+---------------------+---------------------+---------------------+
| 1000000000002101214 | 1000000000001989129 | 1000000000001881637 |
| 1000000000002080453 | 1000000000001968481 | 1000000000001862284 |
| 1000000000002085919 | 1000000000001973677 | 1000000000001866854 |
| 1000000000002075076 | 1000000000001963189 | 1000000000001857288 |
+---------------------+---------------------+---------------------+

我能够从另一个网站找到我的问题的几乎答案,我可以使用以下内容获取表格中字段的列名:

my @cols = @{$sth->{NAME}}; # or NAME_lc if needed 

while (@row = $sth->fetchrow_array) {
    print "@row\n";
}
$sth->finish;

foreach ( @cols ) {
    printf( "Note: col : %s\n", $_ );
}

问题已部分解决。在原始问题中提供的示例表中,我需要知道我的答案所在的列,查询包含几个OR状态:

SELECT * FROM table WHERE (f1='1000000000002101214' OR f2='1000000000002101214' OR f3='1000000000002101214')

我需要结果来显示数字所在的列名是f1。所以....

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

I don't even know where to start

结帐Perl's DBI module。阅读文档。您必须执行以下操作:

#!/usr/bin/perl
 use strict;
 use warnings;
 use DBI;
 #Connect to your database, provide id, password
 my $dbh = DBI->connect('dbi:mysql:perltest','root','password') or die "Connection Error: $DBI::errstr\n";
 #Write your query
 my $sql = "select * from database_schema";
 my $sth = $dbh->prepare($sql);
 #Execute it
 $sth->execute or die "SQL Error: $DBI::errstr\n";
 #Fetch the value
 while (my @row = $sth->fetchrow_array) {
 #Do something with your result
    print "@row\n";
 } 

如果您是Perl的新手,请参阅:http://learn.perl.org/

修改:根据列中的值查询列名。

Select 'f1'

from database_schema

where database_schema.f1 = 1000000000002101214 

union

Select 'f2'

from database_schema

where database_schema.f2 = 1000000000002101214 

union

Select 'f3'

from database_schema

where database_schema.f3 = 1000000000002101214