3

i have this query that works fine

SELECT t.username
FROM users t LEFT JOIN friends y ON t.id=y.user_id2 and y.user_id1=2
WHERE LOWER(t.username) LIKE 'ha%'
ORDER BY 
    CASE WHEN y.user_id2 IS NULL THEN 1 
    ELSE 0 
    END     
    ,t.username;

i'm trying to write it with zend framework and this is what i came up with

        $users = new Users;
        $select = $users->select();
        $select->setIntegrityCheck(false);
        $select->from(array('t1' => 'users'), array('username'));
        $select->joinLeft(array('t2' => 'friends'), 't1.id=t2.user_id2 and t2.user_id1 =2');
        $select->where("LOWER(t1.username) like '$input%'");
        $select->order("t1.username, CASE WHEN t2.user_id2 IS NULL THEN 1 ELSE 0 END ");
        $listofusernames = $users->fetchAll($select);

however it seems not to work and i get this error

Fatal error: Uncaught exception 'Zend_Db_Statement_Mysqli_Exception' with message 'Mysqli prepare error: Unknown column 't1.username, CASE WHEN t2.user_id2 IS NULL THEN 1 ELSE 0 END ' in 'order clause'' in /opt/lampp/htdocs/vote_old/library/Zend/Db/Statement/Mysqli.php:77 Stack trace: #0

apparently it has to do with the case embedded in the order by clause.

do you have any idea how to fix that code ?

thank you

Don Gorgon
  • 2,321
  • 3
  • 18
  • 20

1 Answers1

3

try to put the columns in array like

$select->order(array('t1.username',
              new Zend_Db_Expr ('CASE WHEN t2.user_id2 IS NULL THEN 1 ELSE 0 END')));
akond
  • 15,865
  • 4
  • 35
  • 55
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
  • Fatal error: Uncaught exception 'Zend_Db_Statement_Mysqli_Exception' with message 'Mysqli prepare error: Unknown column 'CASE WHEN t2.user_id2 IS NULL THEN 1 ELSE 0 END' in 'order clause'' – Don Gorgon Jul 25 '11 at 06:06
  • 2
    you need to use Zend_Db_Expr, like http://stackoverflow.com/questions/2162709/zend-db-order-by-field-value – Haim Evgi Jul 25 '11 at 06:10
  • i'm not sure what do u mean by that. can you be more specific please ? – Don Gorgon Jul 25 '11 at 06:12