Answer the question
In order to leave comments, you need to log in
How to write sum of nested subqueries from SQL expression to expression for Zend Framework?
Good afternoon!
In general, there is such a query that adds two responses from nested queries. The first subquery joins the number of likes of one type from two tables, and the second one collects likes of another type from one more table.
I wrote a simple query that does this, but now it needs to be converted to a ZF expression and I'm having trouble with that.
Request:
SELECT
(
SELECT COUNT(*)
FROM `engine4_activity_actions`
INNER JOIN `engine4_activity_likes` ON `engine4_activity_likes`.resource_id = `engine4_activity_actions`.action_id
WHERE `engine4_activity_likes`.poster_id != `engine4_activity_actions`.object_id
AND `engine4_activity_actions`.object_id = 3
) + (
SELECT COUNT(*)
FROM `engine4_core_likes`
WHERE `engine4_core_likes`.user_id = 3
)
AS likes_total;
Answer the question
In order to leave comments, you need to log in
In general, this is not the most beautiful, but working code:
$tableActivityActions = Engine_Api::_()->getDbTable('actions', 'activity');
$tableActivityActionsName = $tableActivityActions->info('name');
$tableActivityLikes = Engine_Api::_()->getDbTable('likes', 'activity');
$tableActivityLikesName = $tableActivityLikes->info('name');
$tableCoreLikes = Engine_Api::_()->getDbTable('likes', 'core');
$tableCoreLikesName = $tableCoreLikes->info('name');
// get sub-select from first table
$selectCoreLikes = $tableCoreLikes->select()
->from($tableCoreLikesName, array('COUNT(*)'))
->where("$tableCoreLikesName.user_id = ?", $user_id)
;
// get sub-select from second table
$selectActivityLikes = $tableActivityActions->select()
->from($tableActivityActionsName, array('COUNT(*)'))
->join($tableActivityLikesName, "$tableActivityLikesName.resource_id = $tableActivityActionsName.action_id", null)
->where("$tableActivityLikesName.poster_id != $tableActivityActionsName.object_id")
->where("$tableActivityActionsName.object_id = ?", $user_id)
;
$db = $tableCoreLikes->getAdapter();
$selectTotalLikes = $db->query('SELECT (' . $selectCoreLikes->__toString() . ') + ('
. $selectActivityLikes->__toString() . ')');
$result = $selectTotalLikes->fetchAll();
$totalLikes = array_shift($result[0]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question