Reputation: 3131
I have a simple query as listed below
SELECT id, name, email FROM users WHERE group_id = 1
This works great until, I then start adding LIKE
queries, chained with OR
statements to the end.
SELECT id, name, email FROM users
WHERE group_id = 1
AND id LIKE $searchterm
OR name LIKE $searchterm
OR email LIKE $searchterm
Suddenly my WHERE
clause is no longer upheld and results with a 'group_id' of 2 or 3 are retrieved.
Is there a way I can group WHERE
clauses so that they are always upheld or am I missing something obvious?
Upvotes: 0
Views: 68
Reputation: 332541
Dealing with the query first - you need to use brackets for the WHERE clause to be interpreted correctly:
SELECT id, name, email
FROM users
WHERE group_id = 1
AND ( id LIKE $searchterm
OR name LIKE $searchterm
OR email LIKE $searchterm)
I'd be looking at using Full Text Search (FTS) instead, so you could use:
SELECT id, name, email
FROM users
WHERE group_id = 1
AND MATCH(id, name, email) AGAINST ($searchterm)
Mind that the USERS
table needs to be MyISAM...
Upvotes: 2
Reputation: 18782
I assume you want
email FROM users WHERE group_id = 1 AND (id LIKE $searchterm OR name LIKE $searchterm OR email LIKE $searchterm)
Here is the mysql operator precedence table
Upvotes: 1