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,888
  • 2
  • 21
  • 40
Jazuly
  • 1,291
  • 3
  • 15
  • 35

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
  • 90,369
  • 161
  • 124
  • 175
Bart Hofland
  • 3,430
  • 1
  • 10
  • 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
  • 90,369
  • 161
  • 124
  • 175
Shefeto
  • 148
  • 1
  • 9