2016-04-13 102 views
3

我想從其他查詢插入到當前查詢得到最大日期。看看我的代碼,請。Symfony組合2查詢

數據:

inv_id inv_date inv_export inv_code 
1  2016-03-14 0   a2 
2  2016-03-13 0   a1 
3  2016-04-13 1   a1 
4  2016-03-14 0   a1 

結果:

for inv_export = 0 return a2 & a1 
for inv_export = 1 return a1 

MySQL的(工作正常):

SELECT ..., i.inv_date, i.inv_export 
FROM Sp.inventory AS i 
... 

WHERE i.inv_date IN (
    SELECT max(i.inv_date) from Sp.inventory WHERE i.inv_export = 1 
); 

我試圖將其轉換爲symfony的:

$qb = $this 
    ->createQueryBuilder('i') 
    ->select('..., i.invDate') 
    ... 

    ->where('i.invExport = :export AND i.invDate = MAX(i.invDate)') 
    ->setParameter('export', $export); 
+0

你可以看看這個[Q/A(http://stackoverflow.com/questions/6637506/doing- a-where-in-subquery-in-doctrine-2),你會發現另一種方法。 –

回答

4

您可以使用子查詢如下:

$sub = $this->createQueryBuilder('i2'); 
$sub->select("max(i2.inv_date)"); 
$sub->where("i.invExport= i2.invExport"); 


$qb = $this 
    ->createQueryBuilder('i') 
    ->select('..., i.invDate') 
    ... 
    ->where('i.invDate = ('.$sub->getDQL().')'); 
    ->andWhere('i.invExport = :export') 
    ->setParameter('export', $export); 

希望這有助於