views:

472

answers:

3

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!

+3  A: 
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
I wasn't sure if the first where could be a `orWhere` so I tested it, it doesn't matter.
Robin
I thought it would be where rather than orwhere - but like you say it doesn't seem to matter! Thanks!
Scoobler
+2  A: 

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

Robin
A: 

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)

pzajdel