我需要在Doctrine中执行下一个查询:
SELECT MAX(LPAD(SUBSTRING(code, 1, instr(code, '/')-1), 6, '0')) as lastCode
FROM provider
WHERE entry_date >= '%s'", date("Y") . "-01-01"
(简而言之:我的代码为xx / yy的提供者,其中yy是2位数年份,xx是序号,因为此代码是varchar我执行查询以获得最后数字今年的代码)
问题在于使用LPAD
。如果我使用查询构建器,则使用自定义函数会出错,如果我使用本机查询,则会得到空结果。
这是我的代码:
使用原生查询:
$sqlMaxCode = sprintf("SELECT MAX(LPAD(SUBSTRING(code, 1, instr(code, '/')-1), 6, '0')) as lastCode
FROM provider
WHERE entry_date >= '%s'", date("Y") . "-01-01");
$nQuery = $em->createNativeQuery($sqlMaxCode, new ResultSetMapping());
$rows = $nQuery->getSingleResult();
$this->get('logger')->info(print_r($rows, true));
//$rows is always empty
使用查询构建器:
$qb = $em->getRepository('AppBundle:Provider')->createQueryBuilder('I');
$qb->select('MAX(LPAD(SUBSTRING(code, 1, instr(code, "/")-1), 6, "0")) as lastCode')
->where("I.entryDate >= ?1")
->setParameter('1', date("Y") . "-01-01");
$result = $qb->getQuery()->getSingleResult();
“查询”构建器会抛出此错误:
错误:预期的已知功能,得到了LPAD'
我还有其他选择吗?为什么本机查询返回空结果? (mysql控制台上的相同查询显示最后一个数字)
注意:我尝试了CAST(MAX(SUBSTRING(...) as unsigned)...
,但CAST
功能遇到了同样的问题。
答案 0 :(得分:0)
我在本机查询中出错,如果我正确配置ERROR: could not create unique index "num_dossier_uniq"
État SQL :23505
Détail :Key (num_dossier, arrondissement_id)=(161/17, 12) is duplicated.
本机查询可以正确处理自定义函数:
ResultSetMapping