如何在mysql中使用and和or

4uqofj5v  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(327)

我想在我的网站上创建一个搜索。在搜索表单中,我有用于搜索的类别和输入查询。例如,在类别im choice jmovies和input query im type关键字中输入ashi。
我的代码

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

所以category=jmovies和keyword=ashi。
例如,我有一张这样的table

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

问题是,因为我选择的是电影,类别戏剧不应该在我的结果,即使戏剧有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

即使im选择jmovies和not fill输入关键字结果也不是只显示jmovies而是显示戏剧。
注意:alt\u name和master\u post\u name有相同的关键字。

x0fgdtte

x0fgdtte1#

我不确定我是否正确理解您的问题,但您可以尝试以下查询:

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

我怀疑这里的“问题”是and运算符的优先级高于or运算符。

vmjh9lq9

vmjh9lq92#

我不是Maven,但给括号一试:

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

看看这个答案:在mysql语句中使用或不使用括号到底有什么区别?

相关问题