donglei2288 2016-08-04 04:37
浏览 96
已采纳

在MySQL / PHP中进行近似搜索匹配的最佳方法是什么?

I'm looking for an effective way to do the following search in MySQL/PHP...

Imagine I have a number of fields in my DB I wish to search on:

User.username
Name.first_name
Address.line1
Phone.number
Email.email_address

I also have the following variables (with example data) in PHP to search with:

$username = "john123";
$name = "john";
$address = "10 fake street";
$phone = "23456789";
$email = "john@johnsemail.com";

Assuming there are 0 complete matches, how would I write a query which could see partial matches and then return results ordered by the number of matches?

For example, using my example data I'd might expect to see a result look something like this,

username | name | address        | phone    | email               | matches
----------------------------------------------------------------------------
john123  | john | 12 new street  | 23456789 | john@johnsemail.com | 4
tim123   | tim  | 10 fake street | 23456789 | tim@timsemail.com   | 2

Just to note, I'm not looking for a wild card search here. I want to return results which have exact matches, just not necessarily a complete match using all DB field. And also want to prioritize the results by the number of matches.

I can think of a very inefficient way of doing it by running each as a separate query, loading that into a PHP array then counting which IDs are found in the most arrays. However, the database running this has millions of records per table, so this wouldn't be feasible at all.

  • 写回答

1条回答 默认 最新

  • donglin7383 2016-08-04 04:46
    关注
    SELECT *, 
      if (username = '$username', 1, 0) +
      if (name     = '$name'    , 1, 0) +
      if (phone    = '$phone'   , 1, 0) +
      if (address  = '$address' , 1, 0) AS matches
    FROM   tab
    ORDER BY matches DESC
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应