来得很晚,但我遇到了同样的问题并以不同的方式解决了它:在JOIN
查询部分,我插入了另一个带有另一个句柄的查询。如果我需要运行的查询类似于
SELECT
st.*, m.measures
FROM tbl_stations st
INNER JOIN (
SELECT
station_id, count(*) AS measures
FROM tbl_measures
GROUP BY station_id
) m ON m.station_id = st.id
然后我为两个查询元素创建句柄
$query = $db->getQuery(true);
$innerSelect = $db->getQuery(true);
然后我创建查询的 joomla 部分:
$query
->select(array('st.*', 'm.measures'))
->from($db->quoteName('#__stations', 'st'))
//here starts the inner join part (note the opening parenthesis)
->innerJoin('(' .
//I perform a canonical select using the second handle
$innerSelect
->select($db->quoteName('station_id'))
->select('count(*) as measures')
->from($db->quoteName('#__measures'))
->group($db->quoteName('station_id'))
//after closing the parenthesis I put an alias for the join
//and then I have the "ON" clause of the join
. ') ' . $db->quoteName('m') . ' ON ' . $db->quoteName('m.station_id') . ' = ' . $db->quoteName('st.id'))
;
就是这个。最终查询(顺便说一句,您可以使用 method 回显它$query->dump()
)如下
SELECT st.*,m.measures
FROM `tbl__stations` AS `st`
INNER JOIN (
SELECT `station_id`,count(*) as measures
FROM `tbl__measures`
GROUP BY `station_id`) `m` ON `m`.`station_id` = `st`.`id`
SELECT
希望这对路过的任何人都有帮助,对使用inside有同样的疑问JOIN
。