具有多个关键字的PHP / MySQL复杂搜索

时间:2012-01-13 10:57:21

标签: php mysql

我在使用php(或mysql)搜索功能时遇到的困难。 我愿意为此买一个剧本,但我找不到。

我有一张客户表(名字,姓氏,街道,邮编,城市等......) 我希望能够不只是寻找一个关键字,而是2 IN 2个不同的列。

例如:

关键字:“John Doe”

所以我的尝试是。

SELECT ....
   WHERE CONCAT(firstname,lastname) LIKE '%john%'
   AND CONCAT(firstname,lastname LIKE '%doe%'

然而:这让我回到了所有的johns并且确实和John Doe先生在这个列表中的某个地方,但不在顶部,尽管它应该是最相关的结果。

我也尝试过:

....
   WHERE MATCH(firstname,lastname) AGAINST('%john doe%')

这几乎可以给出相同的结果。

所以我要找的结果是:

1. John Doe (at first position!)
2. John Miller
3. John Smith
4. Harry Doe
5. Jack Doe
etc......

我一直在寻找2个小时,我拒绝相信我是第一个尝试过这样做的人: - )

感谢任何帮助!

谢谢!

3 个答案:

答案 0 :(得分:3)

你也尝试过这样的事吗

SELECT MATCH(firstname, lastname) AGAINST ('john doe') as Relevance 
FROM table WHERE MATCH(firstname, lastname) AGAINST('john doe' IN
BOOLEAN MODE) 
HAVING Relevance > 0.3
ORDER BY Relevance DESC

另见

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

这也可能是一个解决方案:

SELECT MATCH(firstname) AGAINST ('john doe') as firstname_relevance, 
    MATCH(lastname) AGAINST ('john doe') as lastname_relevance
    FROM table WHERE MATCH(firstname, lastname) AGAINST('john doe' IN
    BOOLEAN MODE) 
    ORDER BY firstname_relevance+lastname_relevance DESC

答案 1 :(得分:0)

喜欢这个吗?

SELECT
   firstname, lastname, othercol, MIN(Weighting)
FROM
    (
    SELECT firstname, lastname, othercol, 1 AS Weighting FROM...
    WHERE firstname = 'john' AND lastname  = 'doe'
    UNION ALL
    SELECT firstname, lastname, othercol, 2 AS Weighting FROM...
    WHERE firstname = 'john' OR lastname  = 'doe'
    ) T
GROUP BY
   firstname, lastname, othercol
ORDER BY
   MIN(Weighting) DESC;

答案 2 :(得分:0)

布尔模式不会按相关性降低的顺序自动对行进行排序,因此您必须:

SELECT MATCH(firstname,lastname) AGAINST('john doe') as Relevance FROM table WHERE MATCH
MATCH(firstname,lastname) AGAINST('john doe'  IN 
BOOLEAN MODE) ORDER 
BY Relevance DESC