10

How would I construct this query using Zend_Db_Select?:

SELECT users.user_id, email_address, t1.value as 'languages'    
FROM users
LEFT JOIN (
  SELECT
    user_id
    , field_id
    , GROUP_CONCAT(value SEPARATOR ',') AS value
  FROM user_multivalued
  WHERE field_id=25
  GROUP BY user_id, field_id) t1
ON t1.user_id = users.users_id
WHERE list_id = 45
Stephen Fuhry
  • 12,624
  • 6
  • 56
  • 55
Oleg
  • 2,733
  • 7
  • 39
  • 62
  • It looks it can be done like this: $subscribers->joinLeft(array($tableAlias => new Zend_Db_Expr('(' . $query . ')' )), $joinCondition, array($fieldInfo['name'] => 'value')); – Oleg Jan 18 '11 at 13:42

1 Answers1

35
$user_multivalued = $db
    ->select()
    ->from('user_multivalued', array(
        'user_id',
        'field_id',
        new Zend_Db_Expr("GROUP_CONCAT(value SEPARATOR ',') AS value")
    ))
    ->where('field = ?', 25)
    ->group('user_id')
    ->group('field_id')
;

$select = $db
    ->select()
    ->from('users', array('user_id', 'email_address'))
    ->joinLeft(
        array('t1' => $user_multivalued),
        't1.user_id = users.user_id',
        array('languages'=>'value')
    )
    ->where('list_id = ?', 45)
;
stollr
  • 6,534
  • 4
  • 43
  • 59
Stephen Fuhry
  • 12,624
  • 6
  • 56
  • 55
  • 1
    Important to note (threw me off while I was trying to figure this out until I found this answer): in the first joinLeft() parameter, make sure you pass it as the Zend_Db_Expr object, not the __toString() version of it. – Ariel Allon Feb 09 '12 at 20:00