我正在重構一個Zend框架應用程序使用原則2.5 DBAL而不是Zend_DB(ZF1)。我有以下Zend_Db的查詢:加入子查詢與教條2 DBAL
$subSelect = $db->select()
->from('user_survey_status_entries', array('userSurveyID', 'timestamp' => 'MIN(timestamp)'))
->where('status = ?', UserSurveyStatus::ACCESSED)
->group('userSurveyID');
$select = $db->select()
// $selectColNames contains columns both from the main query and
// the subquery (e.g. firstAccess.timestamp AS dateFirstAccess).
->from(array('us' => 'user_surveys'), $selectColNames)
->joinLeft(array('firstAccess' => $subSelect), 'us.userSurveyID = firstAccess.userSurveyID', array())
->where('us.surveyID = ?', $surveyID);
這將導致以下MySQL查詢:
SELECT `us`.`userSurveyID`,
// More columns from main query `us`
`firstAccess`.`timestamp` AS `dateFirstAccess`
FROM `user_surveys` AS `us`
LEFT JOIN (
SELECT `user_survey_status_entries`.`userSurveyID`,
MIN(timestamp) AS `timestamp`
FROM `user_survey_status_entries`
WHERE (status = 20)
GROUP BY `userSurveyID`
) AS `firstAccess` ON us.userSurveyID = firstAccess.userSurveyID
WHERE (us.surveyID = '10')
我無法弄清楚如何使用學說2.5查詢生成器加入子查詢。在主查詢中,我需要從子查詢中選擇列。我已閱讀here該原則不支持連接子查詢。如果這仍然是真的,我可以使用doctrine DBAL的SQL查詢構建器以另一種方式編寫此查詢嗎?原生SQL可能對我而言不是一個好的解決方案,因爲此查詢將在代碼中稍後動態擴展。
檢索您的subSelect的結果,然後將其用作您選擇的參數。 – Veve
@Veve subSelect的結果將是一個包含數千個元素的數組,我認爲它不是首先檢索它並將其用作主查詢中的參數的可行方法。 – aimfeld
這是您試圖構建的DQL或SQL嗎? – Ocramius