可以使用Fey :: SQL生成此SQL吗?

时间:2011-08-09 13:41:10

标签: sql perl

我想像这样生成SQL:

SELECT coalesce(max(a.a_index) + 1, 0) as a_index FROM table1 a

我可以获得除“+ 1”之外的所有内容。有没有办法将其添加到查询中?

use strict;

use Fey::Schema;
use Fey::Loader;

use DBI;

my $dbh = DBI->connect("DBI:mysql:....", "...", "...");

my $loader = Fey::Loader->new( dbh => $dbh );

my $s = $loader->make_schema();

my $q = Fey::SQL->new_select();

my $a_table = $s->table('table1')->alias('a');

my $a_index_col = $a_table->column('a_index');

my $max_a_index_func = Fey::Literal::Function->new('max', $a_index_col);
$max_a_index_func->set_alias_name('max_a_index');

my $c_a_index_func = Fey::Literal::Function->new('coalesce', $max_a_index_func, "0");
$c_a_index_func->set_alias_name('a_index');

$q->select($c_a_index_func);
$q->from($a_table);

print $q->sql($dbh);
print "\n";

输出

SELECT coalesce(max(`a`.`a_index`), 0) AS `a_index` FROM `table1` AS `a`

2 个答案:

答案 0 :(得分:0)

我认为你不能,因为Column,Literal和Function对象没有操作将它们链接在一起(除了Function之外我也看不到任何可以做到这一点的类)。

我可以通过代码生成看到的唯一解决方法是创建一个存储函数:

CREATE FUNCTION plus_one (n INT)
RETURNS INT DETERMINISTIC
RETURN COALESCE(n + 1, 0);

然后使用此函数代替coalesce:

my $c_a_index_func = Fey::Literal::Function->new('plus_one', $max_a_index_func);
$c_a_index_func->set_alias_name('a_index');

答案 1 :(得分:0)

一旦你停止使用Fey :: Literal :: Function进行修改并只使用Fey :: Literal :: Term,这实际上非常简单。只需这样做:

my $c_a_index_func = Fey::Literal::Term->new('coalesce(max(', $a_index_col, ') + 1, 0)');
$c_a_index_func->set_alias_name('a_index');

您的$max_a_index_func可以完全消失。

相关问题