0

So i'm working on this site and i just added a search button. Everything works fine when i use a simple search query like

SELECT `student_id` FROM `student` WHERE `username` LIKE 'jo%' OR `firstname` LIKE 'jo%' OR `lastname` LIKE 'jo%' OR `surname` LIKE 'jo%' OR `email` LIKE 'jo%' 

This will return all id with a name that matches john from a database by looking at the fields 'username', firstname, lastname, and so on.

Th problem however is, when the user inserts a space between the search parameter (which in essence means he is searching a student by both names), the result is nothing.

I figured that this is because the it is looking for the search parameter (say, 'john doe') independently in each field.

How do i work around this.

4

5 回答 5

2

我不确定你想如何处理这些,你可以将它添加到你的 WHERE 子句中,以搜索名字和姓氏字段,它们之间有一个空格。

CONCAT(`firstname`, ' ', `lastname`) LIKE 'jo%'

或者您可能想要删除通配符并进行精确搜索。

CONCAT(`firstname`, ' ', `lastname`) = 'jo'
于 2013-10-04T18:29:16.080 回答
0

如果您想跨多个列进行搜索/匹配,您确实需要研究 MySQL 全文搜索功能。请参阅此链接以获取帮助您入门的文档:

http://dev.mysql.com/doc/refman/5.5/en/fulltext-natural-language.html

这将比尝试LIKE跨越一堆列更好地扩展。

于 2013-10-04T18:25:52.453 回答
0
SELECT * FROM student 
    WHERE username LIKE REPLACE(username, ' ', '') = REPLACE("Twitt er", ' ', '')
于 2013-10-04T18:29:15.727 回答
0

您可以假设空格的存在意味着用户正在搜索名字/姓氏组合。(实际上您的 UI 可以说明这一点)。

然后使用

$name = split(' ' , $incoming);

然后你创建一个条件检查 $name[1] 是否存在,然后确定是否搜索

$where_clause = WHERE firstname = $name[0] AND lastname = $name[1];

如果失败,请退回到:

$where_clause = WHERE firstname = $name[0] 

或者

$where_clause = WHERE lastname = $name[1] 

等等。

然后像这样使用它:

SELECT `student_id` FROM `student` . $where_clause

这有点伪代码,但你得到了我希望的图片。

有更优雅的方法可以实现这样的sql-builder.,但我提供它是为了说明您如何开始考虑它——“使用 FULLTEXT”评论放在一边。

于 2013-10-04T18:33:10.960 回答
0

有两种方法可以做到这一点:

1)当你试图

`

     $search_term= "Mike Brant";
      $term_part = preg_split('/ /', $search_term);
     /*
      term_part[0]=Mike
      term_part[1]=Brant
    */
     foreach($term_part as $value){
    $like. = " `username` LIKE '".$value."%' OR `firstname` LIKE '".$value."%' OR `lastname` LIKE '".$value."%' OR `surname` LIKE '".$value."%' OR `email` LIKE '".$value."%' OR "
    }
    $like = substr($like, 0, -3);
    $sql = "SELECT `student_id` FROM `student` WHERE ".$like.";
`

2) 使用 FULLTEXT 查表引擎 MISAM 了解更多关于FULLText

FULLTEXT 是搜索应用程序的最佳选择

于 2013-10-04T18:43:55.263 回答