2016-01-04 35 views
1

enter image description hereZF2表网关连接查询从第二个表

嗨只获取最新的行(通过ID),我需要一个ZF2加入第二个表查询(按id DESC)获取只有最后一排。我写了一个SQL查询,它的工作原理。

SELECT st1.customer_id, 
    st1.id 
    FROM status st1 
    inner JOIN 
    (
    SELECT max(id) MaxId, customer_id 
    FROM status 
    GROUP BY customer_id 
) st2 
    ON st1.customer_id = st2.customer_id 
    AND st1.id = st2.MaxId 

但我需要在zend框架2表格网关格式这个查询。请帮忙。

回答

1
use Zend\Db\Sql\Select; 
    use Zend\Db\Sql\Expression; 

    $sql = new Select(); 
    $sql->columns(["customer_id", new Expression ("max(id) AS MaxId")]) 
     ->from ('status') 
     ->group('customer_id'); 

    $outer = new Select(); 
    $outer->columns (['customer_id', 'id']) 
     ->from (['st1' => 'status']) 
     ->join (['st2' => $sql], 
      'st1.customer_id = st2.customer_id AND st1.id = st2.MaxId', []); 
+0

谢谢@akond它的工作除了 新的表达式( “MAX(ID)AS MaxId”) 这一个。我认为我们应该使用'MaxId'=>新的Expression(“max(id)”)来代替它。 – murad

相关问题