使用OR条件进行全文搜索的Mysql查询

时间:2013-09-27 19:40:38

标签: php mysql sql match-against

我有一个下拉列表,其中只包含两个选项AndOr。选择后这两个选项将运行查询,具体取决于选择。选择And后,将进行查询更改。我的查询看起来像这样,

$sql = 
            "SELECT distinct n.node_id, n.path, 
               n.title_tag as node_name, 
               n2.title_tag as tree_name,
               MATCH (n.title_tag) AGAINST ('%s') as score
            FROM nodes n 
               join trees t on (n.tree_id=t.tree_id and t.status='A' and t.workspace_id=%d)
               join nodes n2 on (n2.node_id = t.tree_id)
               left join node_links nl1 on (n.node_id=nl1.from_node_id and nl1.to_node_id='%s')
               left join node_links nl2 on (n.node_id=nl2.to_node_id and nl2.from_node_id='%s')
            WHERE n.node_id!='%s' and nl1.node_link_id is null and nl2.node_link_id is null
            HAVING score > 0
            ORDER BY score DESC";

请注意MATCH AGAINST部分,即我要添加AndOr条件的位置。如果在选择And条件时查询将使用node_name逻辑与AND匹配,并且在选择Or条件时查询将与{node_name匹配,我将如何操作? 1}}使用OR逻辑。任何帮助都可以。感谢。

1 个答案:

答案 0 :(得分:2)

AFAIU你要根据前端选择(存储在$condition)中添加条件的问题,如果有,那么请尝试下面的代码:(未测试)

switch($condition) {
                case "AND" : $searchNode = "+$searchTerm"; break;
                case "OR"  : 
                default    :
                             $searchNode = "$searchTerm"; break;
}

$final_search = "$searchTitle $searchNode";

$sql = "SELECT distinct n.node_id, n.path, 
                   n.title_tag as node_name, 
                   n2.title_tag as tree_name,
                   MATCH (n.title_tag,n.node_name) 
                   AGAINST ($final_search IN BOOLEAN MODE) as score ..." ;

Reference

相关问题