mysql查询计算like运算符与每列匹配的次数

时间:2015-09-22 19:08:40

标签: mysql sql

$sql ="SELECT * 
       FROM members m 
       INNER JOIN author_details a 
          on m.email= a.email 
       where m.name like '".$search_text."%' 
          or a.username like '".$search_text."%' 
          or a.address_line1 like '%".$search_text."%' 
          or a.address_line2 like '%".$search_text."%' 
          or a.city like '%".$search_text."%' 
          or m.phone = ".(int)$search_text."

所以我正在寻找的是计算哪个列具有最高匹配然后首先返回该结果集,例如,如果找到关键字在地址列中匹配最多则结果集应该包含地址匹配结果,现在结果是首先显示名称,即使它们很少。

我对sql不太了解所以请尽量保持简单

1 个答案:

答案 0 :(得分:0)

比较运算符在匹配时会返回1,因此您可以使用SUM()来添加它们。

$sql ="SELECT
            SUM(m.name like '".$search_text."%') AS name_matches,
            SUM(a.username like '".$search_text."%') AS username_matches,
            SUM(a.address_line1 like '%".$search_text."%') AS addr1_matches,
            SUM(a.address_line2 like '%".$search_text."%') AS addr2_matches,
            SUM(a.city like '%".$search_text."%') AS city_matches,
            SUM(m.phone = ".(int)$search_text.") AS phone_matches
       FROM members m 
       INNER JOIN author_details a 
          on m.email= a.email";

每个_matches列都将包含搜索文本在该列中匹配的行数。