我正在尝试在ZF 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 :(得分: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();