2016-01-04 36 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

相關問題