Marko Vasic
Marko Vasic

Reputation: 301

Query with three conditions

I need to make query that will select all names and all nicknames from some table but only where id is in some array.This is The query:

SELECT n. * FROM nikovi n 
INNER JOIN sajt_nikovi s ON n.id = s.nik
WHERE s.sajt = '50' and     n.nadimak like '%ana%' or n.ime like '%ana%'

And it found all entries from table where n.ime like '%ana%', not only those for this join. does anyone have any idea?

Upvotes: 0

Views: 877

Answers (3)

Michael Bartel
Michael Bartel

Reputation: 191

Always use brackets, when you mix AND and OR

SELECT n. * FROM nikovi n INNER JOIN sajt_nikovi s ON n.id = s.nik WHERE s.sajt = '50' AND (n.nadimak LIKE '%ana%' OR n.ime LIKE '%ana%')

Upvotes: 0

billyonecan
billyonecan

Reputation: 20270

Group your OR:

SELECT n. * 
FROM nikovi n 
INNER JOIN sajt_nikovi s 
ON n.id = s.nik 
WHERE s.sajt = '50' 
AND (n.nadimak LIKE '%ana%' OR n.ime LIKE '%ana%')

Upvotes: 1

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

AND binds harder than OR, which means that that it will evaluate something like;

WHERE (s.sajt = '50' and n.nadimak like '%ana%') or n.ime like '%ana%'

If you mean something else, you need to add parenthesis to make it clear to the database. In this case, you will need to change it to;

WHERE s.sajt = '50' and (n.nadimak like '%ana%' or n.ime like '%ana%')

Upvotes: 4

Related Questions