1

i want to create a search in my web. in search form i have Category and Input query for search. for example in category im choice jmovies and in input query im type keyword for ashi.

my code

SELECT * 
FROM master_post 
WHERE category = 'jmovies' 
    AND master_post_name LIKE '%ashi%' 
    OR altname LIKE '%ashi%'

so category = jmovies and keyword = ashi.

for example i have table like this

category     master_post_name    alt_name
===========  ==================  ===============
JMovies      ashi_include_1      not_include
JMovies      ashi_include_2      not_include
JMovies      ashi_include_3      not_include
JMovies      not_include         ashi_include_1
JMovies      not_include         not_include
Drama        ashi_in_drama       ashi_include_2

if i run with that code result is

category     master_post_name    alt_name
===========  ==================  ===============
JMovies      ashi_include_1      not_include
JMovies      ashi_include_2      not_include
JMovies      ashi_include_3      not_include
JMovies      not_include         ashi_include_1
Drama        ashi_in_drama       ashi_include_2

the problem is, cause im choice jmovies, category drama should not be in my result, even if drama have ashi in master_post or alt_name.

result must be like this

category     master_post_name    alt_name
===========  ==================  ===============
JMovies      ashi_include_1      not_include
JMovies      ashi_include_2      not_include
JMovies      ashi_include_3      not_include
JMovies      not_include         ashi_include_1

even if im choice jmovies and not fill input keyword result is not showing only jmovies but it showing drama too.

NOTE: alt_name and master_post_name have same keyword.

Sloan Thrasher
  • 4,953
  • 3
  • 22
  • 40
Jazuly
  • 1,374
  • 5
  • 20
  • 43

2 Answers2

2

I'm not sure if I understand your question correctly, but you may try the following query:

SELECT * FROM master_post 
WHERE category = 'jmovies' AND (master_post_name LIKE '%ashi%' OR altname LIKE '%ashi%')

I suspect that the "problem" here is the fact that the AND operator has a greater precedence than the OR operator.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Bart Hofland
  • 3,700
  • 1
  • 13
  • 22
1

I'm not an expert but give parenthesis a go:

SELECT * FROM master_post 
WHERE category = 'jmovies' AND (master_post_name LIKE '%ashi%' OR altname LIKE '%ashi%')

see this answer: How exactly does using OR in a MySQL statement differ with/without parentheses?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Shefeto
  • 178
  • 1
  • 10