何时使用OR,AND在MYSQL中进行高级搜索查询结果

时间:2012-01-25 16:39:25

标签: mysql variables

我正在尝试为我们的网站构建一个高级搜索选项。我无法让这个工作?基本上唯一需要保持不变的是' review_live = 1 ',其余的只有在用户搜索它时才会这样。为什么这不正常,也许我没有使用OR,并且在更长的查询中正确使用...

    WHERE 
    review_live = 1 AND
    city LIKE '%$location%' OR 
    region LIKE '%$region%' OR 
    date BETWEEN '$beginDate' AND '$endDate' OR
    name LIKE '%$name2%' OR
    type LIKE '%$type1%' OR 
    type_2 LIKE '%$type2%' 
    ORDER BY date DESC

2 个答案:

答案 0 :(得分:5)

第一个建议:

WHERE 
review_live = 1 AND 
(
  city LIKE '%$location%' OR
  region LIKE '%$region%' OR 
  ( date BETWEEN '$beginDate' AND '$endDate' ) OR
  name LIKE '%$name2%' OR
  type LIKE '%$type1%' OR
  type_2 LIKE '%$type2%' 
)
ORDER BY date DESC

编辑:

如果用户不想过滤该条件,我猜你用like替换所有'%'个字符串。然后试试这个:

WHERE 
review_live = 1 AND 
city LIKE '%$location%' AND 
region LIKE '%$region%' AND 
date BETWEEN '$beginDate' AND '$endDate' AND
name LIKE '%$name2%' AND
type LIKE '%$type1%' AND
type_2 LIKE '%$type2%'
ORDER BY date DESC

答案 1 :(得分:0)

你想要review_live = 1和其他所有东西。所有其他的东西都是城市或地区,或者......

WHERE     review_live = 1 AND (...)     ORDER BY date DESC