MYSQL PHP按最佳匹配返回的顺序来自多列中的多个单词

时间:2018-04-05 14:40:13

标签: php mysql ajax

我正在进行Ajax搜索,用户可以使用PHP MYSQL AJAX搜索多个单词,如“ pa a s

以此表为例:

+----+-----------+-----------+----------+---------+------------+
| id |   name    |   city    | country  |  type   |   status   |
+----+-----------+-----------+----------+---------+------------+
|  1 | howard    | eugene    | usa      | person  | publish    |
|  2 | john      | paris     | france   | person  | publish    |
|  3 | marco     | lisbon    | portugal | person  | publish    |
|  4 | paula     | madrid    | spain    | person  | publish    |
|  5 | josé      | barcelona | spain    | person  | publish    |
|  6 | hanna     | berlin    | germany  | person  | publish    |
|  7 | paolo     | torino    | italy    | person  | publish    |
|  8 | laurence  | monaco    | france   | company | publish    |
|  9 | giovanni  | bergamo   | italy    | company | publish    |
| 10 | manuel    | porto     | portugal | person  | publish    |
| 11 | maurizio  | beijing   | china    | company | publish    |
| 12 | mario     | são paulo | brazil   | person  | notpublish |
+----+-----------+-----------+----------+---------+------------+

在此表中,我只想要类型的结果和状态发布

查询:

SELECT * FROM table 
WHERE type="person" 
AND status="publish" 
AND (name LIKE "%pa%" OR city LIKE "%pa%" 
    OR country LIKE "pa%" 
    OR name LIKE "%a%" 
    OR city LIKE "%a%" 
    OR country LIKE "%a%" 
    OR name LIKE "%s%" 
    OR city LIKE "%s%" 
    OR country LIKE "s%" 
)

通过一个循环它会根据空间爆炸字符串并生成这个sql代码,所以基本上它会尝试在3列(9个搜索)中找到3个单词。

$words = explode(" ", 'pa a s'); //'pa'; 'a'; 's';

问题是,我想按发现次数排序。例如: 字符串“pa”位于“name”列中,ID为:4,7 字符串'pa'位于“city”列中,ID为:2 字符串“pa”位于“country”列中,ID为:4,5

字符串'a'位于'name'列中,ID为:1,3,4,6,7,10 字符串'a'位于“city”列中,ID为2,4,5 字符串'a'位于“country”列中,ID为:1,2,3,4,5,6,7,10

字符串's'位于'name'列中,ID为:5 字符串's'位于'city'列中,ID为2,3 字符串's'位于“country”列中,ID为:1,4,5

订单应该是:

The ID 4 was matched: 6 Times
The ID 5 was matched: 5 Times
The ID 2 was matched: 4 Times
The ID 1 was matched: 3 Times
The ID 3 was matched: 3 Times
The ID 7 was matched: 3 Times
The ID 6 was matched: 2 Times
The ID 10 was matched: 2 Times

0 个答案:

没有答案