SQL add where子句进行查询

时间:2018-05-03 15:07:17

标签: sql join where

我有一个连接两个表的SQL查询并返回到目前为止工作正常的结果。它看起来像这样:

Select * 
From program_recipes ptr 
Left Join recipes r On ptr.recipe_id = r.id 
Where ptr.program_type_id In (2) 
  And r.available = 1

现在我想添加一个where子句,检查标题是否包含一个单词。我到目前为止尝试了这个,但是我遇到了语法错误:

Select * 
From program_recipes ptr 
Left Join recipes r On ptr.recipe_id = r.id 
Where ptr.program_type_id In (2) 
  And r.available = 1 
   Or Where r.title LIKE '%word%'
   Or Where r.title LIKE '%word%'

2 个答案:

答案 0 :(得分:1)

删除额外的命令和add()

Select * 
From program_recipes ptr 
Left Join recipes r On ptr.recipe_id = r.id 
Where ptr.program_type_id In (2) 
  And (r.available = 1 
   Or   r.title LIKE '%word%'
   Or   r.title LIKE '%word%')

答案 1 :(得分:0)

不要重复WHERE,只需要一次。请查看逻辑运算符ANDOR之间的优先级以满足您的需求(如果需要,请添加括号)。

Select 
    * 
From 
    program_recipes ptr 
    Left Join recipes r On ptr.recipe_id = r.id 
Where 
    r.available = 1 AND
    (
        ptr.program_type_id In (2) OR
        r.title LIKE '%word%'
    )
相关问题