我想在我的网站上创建搜索。在搜索表单中,我有搜索的类别和输入查询。例如,在类别中选择 jmovies ,在 ashi 的输入查询im类型关键字中。
我的代码
SELECT *
FROM master_post
WHERE category = 'jmovies'
AND master_post_name LIKE '%ashi%'
OR altname LIKE '%ashi%'
所以category = jmovies 和keyword = ashi 。
例如我有这样的表
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
如果我使用该代码运行结果是
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
问题是,因为我选择 jmovies ,类别戏剧不应该在我的结果中,即使戏剧在 ashi > master_post 或 alt_name 。
结果必须像这样
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 而未填写输入关键字,结果也不仅仅显示jmovies,但它也显示戏剧。
注意: alt_name 和 master_post_name 具有相同的关键字。
答案 0 :(得分:1)
我不是专家,但请给括号:
SELECT * FROM master_post
WHERE category = 'jmovies' AND (master_post_name LIKE '%ashi%' OR altname LIKE '%ashi%')
请参阅此答案:How exactly does using OR in a MySQL statement differ with/without parentheses?
答案 1 :(得分:1)
我不确定我是否理解您的问题,但您可以尝试以下查询:
SELECT * FROM master_post
WHERE category = 'jmovies' AND (master_post_name LIKE '%ashi%' OR altname LIKE '%ashi%')
我怀疑"问题"这里的事实是AND运算符的优先级高于OR运算符。