2

I am trying to build the following SQL statement:

SELECT `users_table`.*, `users_data`.`first_name`, `users_data`.`last_name`
FROM `users_table`
INNER JOIN `users_data` ON users_table.id = user_id
WHERE (users_table.username LIKE '%sc%')
OR (users_data.first_name LIKE '%sc%')
OR (users_data.last_name LIKE '%sc%')

I have the following code at the moment:

public function findAllUsersLike($like) {
    $select = $this - > select(Zend_Db_Table::SELECT_WITH_FROM_PART) - > setIntegrityCheck(false);
    $select - > where('users_table.username LIKE ?', '%'.$like.'%');
    $select - > where('users_data.first_name LIKE ?', '%'.$like.'%');
    $select - > where('users_data.last_name LIKE ?', '%'.$like.'%');
    $select - > join('users_data', 'users_table.id = user_id', array('first_name', 'last_name'));
    return $this - > fetchAll($select);
}

This is close, but not right as it uses AND to add the extra WHERE statements, instead of OR.

Is there any way to do this as one select? Or should I perform 3 selects and combine the results (alot more overhead?)?

P.S. The parameter $like that is past is sanitized so don't need to wory about user input in the code above!

Scoobler
  • 9,696
  • 4
  • 36
  • 51

3 Answers3

4
public function findAllUsersLike($like) {
    $select = $this->select(Zend_Db_Table::SELECT_WITH_FROM_PART)->setIntegrityCheck(false);
    $select->orWhere('users_table.username LIKE ?', '%'.$like.'%');
    $select->orWhere('users_data.first_name LIKE ?', '%'.$like.'%');
    $select->orWhere('users_data.last_name LIKE ?', '%'.$like.'%');
    $select->join('users_data', 'users_table.id = user_id', array('first_name', 'last_name'));
    return $this->fetchAll($select);
}
St.Woland
  • 5,357
  • 30
  • 30
  • 1
    I wasn't sure if the first where could be a `orWhere` so I tested it, it doesn't matter. – Robin Jan 18 '10 at 15:21
  • I thought it would be where rather than orwhere - but like you say it doesn't seem to matter! Thanks! – Scoobler Jan 18 '10 at 15:43
2

Zend_Db_Select has a function orWhere. You should be able to solve your problem with it.

Robin
  • 303
  • 5
  • 17
-1

You can also nest OR statements using double quotes ("):

$select->where('
users_table.username LIKE ' "%'.$like1.'%" '
OR users_data.first_name LIKE '"%'.$like2.'%" '
OR users_data.last_name LIKE '"%'.$like3.'%"'
);

Which works better when you create sql including also AND like:

select X from Y where A = AAA and (B = BBB or C = CCC or D = DDD)