MySQL使用IN,LIKE和OR

时间:2015-03-01 12:46:46

标签: php mysql search

我正在尝试编写一个搜索算法,没有太高级但它不仅仅是WHERE field1 ='searchtext'。我正在尝试搜索多个字段中的所有关键字。

我做了一些搜索,似乎我对这个问题的看法不符合MySQL对其他函数的'IN'的使用,但是我找不到任何似乎在stackoverflow上提出更好的方法或在独立的博客和其他教程网站上使用谷歌。

$fields = array('type','suburb','postcode','address');      // Fields in db being searched
$queried = $db->real_escape_string($_REQUEST['keyword']);   // Input from form
$keys = explode(" ",$queried);                              // Determine individual keywords
$sql = "SELECT * FROM `properties` WHERE ";                 // Beginning of SQL Statement

$frc = 0;    // Field Counter
foreach($fields as $f){
$inner = ''; // Reset $inner each run
$irc = 0;    // Reset Inner Counter each run
$frc++;      // Increase Field Counter
if($frc != 1){ $sql .= " OR "; }    // All except first runthrough
$sql .= "`".$f."` IN ";             // `field` IN
    foreach($keys as $k){
        $irc++;                     // Increase inner counter
        if($irc == 1){
            $inner .= "('%".$k."%'";    // First Inner per run (aka each keyword)
        }else{
            $inner .= ", '%".$k."%'";   // All other Inners
        }
    }
    $inner .= ")";  // Inner finishes run before reset
$sql .= $inner;     // Add Inner to SQL ready for query
}
$sql .= ";";        // Clean finish to SQL statement

$SearchProperties = $db->query($sql);   // Run Query

我收录了评论,以帮助您理解我的杂乱代码以及我觉得我在做什么。代码给了我预期的输出,例如,如果我搜索关键字“house”,我的输出如下;

$queried = house 3064
$sql = SELECT * FROM `properties` WHERE `type` IN ('%house%', '%3064%') OR `suburb` IN ('%house%', '%3064%') OR `postcode` IN ('%house%', '%3064%') OR `address` IN ('%house%', '%3064%'); 

type列内有房屋和联排别墅,它应该能够同时击中两者,并且应该使用邮政编码3064点击任何东西,无论它是否在另一列中有房子(根据我想要完成的内容) )

然而,经过几个小时的搜索,尽管我的输出是合乎需要的,但我不相信它是正确的。任何人都可以帮助阐明解决我的quandry的正确方法以及为什么这不起作用?我总是喜欢理解并从这些误解中学习。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

如果您有通配符,则需要like而不是in

SELECT *
FROM `properties`
WHERE (`type` LIKE '%house%') OR
      (`suburb` LIKE '%house%') OR
      (`postcode` LIKE '%house%') OR
      (`address` LIKE '%house%'); 

但是,我强烈建议您调查全文索引(请参阅here)。使用MATCH()可以大大简化您的工作。

编辑:

您的查询仍然不正确。你仍然应该使用like

SELECT *
FROM `properties`
WHERE (`type` LIKE '%house%' or type like '%3064%') OR
      (`suburb` LIKE '%house%' or suburb like '%3064%') OR
      (`postcode` LIKE '%house%' or postcode like '%3064%') OR
      (`address` LIKE '%house%' or address like '%3064%'); 

答案 1 :(得分:0)

尝试将'IN'更改为'LIKE'。 例如

$queried = house
$sql = SELECT * FROM `properties` WHERE 
   `type` LIKE '%house%' 
OR `suburb` LIKE '%house%' 
OR `postcode` LIKE '%house%' 
OR `address` LIKE '%house%';

如果您有多个关键字,则需要更改查询。 例如

$queried = house 3064
$sql = SELECT * FROM `properties` WHERE 
   (`type` LIKE '%house%' AND `type` LIKE '%3064%') 
OR (`suburb` LIKE '%house%' AND `suburb` LIKE '%3064%') 
OR (`postcode` LIKE '%house%' AND `postcode` LIKE '%3064%') 
OR (`address` LIKE '%house%' AND `address` LIKE '%3064%');