2013-09-25 74 views
2

我想在ZF 2.運行一個特殊的SQL查詢Zend框架2 - SQL子查詢

SELECT listingId, COUNT(*) as num 
FROM 
(SELECT DISTINCT listingId, locationId 
FROM l_f_locations 
WHERE locationId IN (7, 9, 10)) AS foo 
GROUP by listingId, HAVING num = 3 

我第一次嘗試創建子查詢,因爲它是一個完整的MySQL查詢,但後來卻沒把它融入主要查詢。我無法將子查詢別名「AS foo」,因爲這是完成SQL squery工作的要求。

任何想法?

+0

你可以在這裏找到你的答案。 http://tarunlinux.blogspot.in/2013/11/zf2-zenddbsqlexpression-usage.html –

回答

4

首先,你可以做到這一點沒有一個子查詢:

SELECT listingId, COUNT(DISTINCT locationId) AS num 
FROM l_f_locations 
WHERE listingId IN(7,9,10) 
GROUP BY listingId 
HAVING num = 3; 

對於未來的參考,但是,你可以做你提到使用一對Zend_Db_Select對象的對象,一個子查詢查詢和另一個爲主:

$subQuery = $dbAdapter->select() 
    ->from('l_f_locations', array('listingId', 'locationId')) 
    ->where('locationId IN(7,9,10)') 
    ->group('listingId') 
    ->group('locationId'); 

$select = $dbAdapter->select() 
    ->from($subQuery, array('*', 'num' => 'COUNT(*)')) 
    ->group('listingId') 
    ->having('num = 3'); 

$result = $select->query()->fetchAll(); 
+0

Zend的例子是針對ZF1的,儘管問題清楚地表明它是關於ZF2的。我剛剛問了一個關於ZF2的類似問題:http://stackoverflow.com/questions/25606544/zend-db-select-from-subquery –

+0

$ select = $ dbAdapter-> select() - > from(array('t ',$ subQuery)) - > columns('array'('*','num'=>'COUNT(*)')) -join('t2','t2.id = t1.id' - > ('listingId') - > having('num = 3'); – mpoletto

+0

$ select = $ dbAdapter- > select() - > from(array('t',$ subQuery)) - > columns('*','num'=>'COUNT(*)')) -join('t2' ,'t2.id = t1.id' - > group('listingId') - > having('num = 3' ); – mpoletto