SQL LIKE查询匹配字符串中的任何单个单词

时间:2011-05-04 01:51:01

标签: php mysql sql sql-like

我正在尝试查询:

$title2 = (isset($row_DetailRS1['r_bus_name']) ? $row_DetailRS1['r_bus_name'] : "");

$query_test = "SELECT * 
                 FROM table 
                WHERE r_email = '$email2' 
                  AND r_city != '$location2' 
                  AND r_bus_name LIKE '%$title2%' 
             ORDER BY r_bus_name";

r_bus_name LIKE '%$title2'是从上面定义的,并从POST中获取EVENT的TITLE。标题通常是两到三个字......

如何查询r_bus_name LIKE (any of the words in the event title $title2)

因为现在它正在取得$ title2的全部价值..我需要将它们分开或用文字来爆炸它们,所以如果标题是“测试标题在这里”,那么“Tester title here”会匹配吗?

3 个答案:

答案 0 :(得分:0)

假设该表是MyISAM,您可以使用native Full Text Search (FTS) functionality

$query = sprintf("SELECT t.* 
                    FROM YOUR_TABLE t
                   WHERE t.r_email = '%s' 
                     AND t.r_city != '%s' 
                     AND MATCH(t.r_bus_name) AGAINST('%s')
                ORDER BY t.r_bus_name",
                 mysql_real_escape_string($email2),
                 mysql_real_escape_string($location2),
                 mysql_real_escape_string($title2) );

$result = mysql_query($query);

可悲的是,MySQL不支持InnoDB引擎上的FTS。

附录

如果您没有将PDO / etc用于预准备语句,我建议使用sprintf,以防止SQL注入攻击。

答案 1 :(得分:0)

在空格上拆分title2并做多个喜欢:

$titleArray = split(" ", $title2);

$query_test = "SELECT * 
                 FROM table 
                WHERE r_email = '$email2' 
                 AND r_city != '$location2'
                 AND ("
    foreach ($title as titleArray)
        $query_test .= "OR r_bus_name LIKE '%$title%'" 
$query_test .= "ORDER BY r_bus_name";

答案 2 :(得分:0)

如果要搜索标题中单词的 EACH ,则需要使用 OR 操作构建查询,以将它们应用于同一查询。

它可能看起来像这样:

// break apart the title using spaces
$title2 = (isset($row_DetailRS1['r_bus_name']) ? $row_DetailRS1['r_bus_name'] : "");
$title_keywords = explode(" ", $title2);

// construct conditions (Note the ampersand causes pass-by-reference)
foreach($title_keywords as &$keyword) {
    $keyword = "r_bus_name LIKE '%".mysql_real_escape_string($keyword)."%'";
}
$keyword_search = "(" . implode(" OR ", $title_keywords) . ")";

$query_test = "SELECT * 
    FROM table 
    WHERE r_email = '".mysql_real_escape_string($email2)."' 
        AND r_city != '".mysql_real_escape_string($location2)."' 
        AND ".$keyword_search." 
    ORDER BY r_bus_name";

// ...