0

I'm trying to realize the following query with zend db select:

SELECT `uac`.`uid`, `u`.`uid`, `g`.`groupid`, `g`.`packageid` 
FROM `user_has_data` AS `uac` 
INNER JOIN `users` AS `u` ON u.uid = uac.uid 
LEFT JOIN (`user_in_group` AS `uig` 
  INNER JOIN `groups` AS `ag` ON (ag.groupid = uig.groupid) AND (ag.packageid = 2) 
 ) AS `g` ON uac.uid = g.uid
WHERE (uac.dataid = '3') AND (u.uname LIKE 'test%')
GROUP BY `u`.`uid`

I got the following, but got stuck when trying to convert the nested join to zend structure:

$select = $db->select()->from(array('uac' => 'user_has_data'), array('uac.uid'))
->join(array('u' => 'users'), 'u.uid = uac.uid', array('uid', 'uname'))
->joinLeft(array('uig' => 'user_in_groups'), 'uig.uid = uid', array('agid' => 'uig.groupid'))
->join(array('ag' => 'groups'), '(ag.agid = uig.groupid) AND ( ag.packageid = '.$packageid.')', array('packageid'))
->where('uac.dataid = ?', $dataid)
->where('(u.uname LIKE ?)', $value)
->group('u.uid');

Is it possible to get the given sql query into a suitable structure for zend db select? I need a select object for further handling in a paginator, so if this is not possible I have to make a straight forward sql query.

Shaeldon
  • 873
  • 4
  • 18
  • 28
max
  • 13
  • 3

2 Answers2

0

I know the question is old, but i think people might still benefit from the right answer for this question.

That nested join is the same as

 SELECT * FROM `user_in_group` AS `uig` 
 INNER JOIN `groups` AS `ag` ON (ag.groupid = uig.groupid) AND (ag.packageid = 2) 

So this should work just fine.

$subquery = $db->select()
->from(array('uig' => 'user_in_groups'),'*')
->joinInner(array('ag'=>'groups'),'(ag.groupid = uig.groupid) and (ag.packegeid = 2)',array('*'));

$select = $db->select()->from(array('uac' => 'user_has_data'), array('uac.uid'))
->join(array('u' => 'users'), 'u.uid = uac.uid', array('uid', 'uname'))
->joinLeft('g'=>$subquery), 'uac.uid = g.uid', array('g.groupid', 'g.packageid'))
->where('uac.dataid = ?', $dataid)
->where('(u.uname LIKE ?)', $value)
->group('u.uid');
Iberê
  • 1,211
  • 1
  • 11
  • 16
  • 1
    This is true, but performance will often be much worse, particularly in MySQL which handles subqueries in joins very badly – limos Jun 27 '13 at 08:53
0

I don't believe you can do a nested join like that with Zend_Db_Select. Your best bet is to create your own paginator adapter (it's easier than you might think, look at the Select one) and manage the LIMIT part of the SQL yourself.

David Snabel-Caunt
  • 57,804
  • 13
  • 114
  • 132