2010-03-11 82 views
1

任何人都可以帮助我如何按以下标准对行进行相关性排序吗?MySQL搜索(按相关性排序)

`tbluser` 
- - - - - - - 
First Name 
Last Name 

`tbleduc` 
- - - - - - - 
School 
College 
University 

在搜索表单用户以下字段

Name 
School 
College 
University 

凡学校学院和大学是可选..

而且名称被分成2个字(在中间换句话说省略),第一个字作为第一ANME和最后一个字作为姓​​氏..

现在我想实现基于相关性的搜索。

感谢您的帮助:)

回答

5

好吧,我想这对你的Postgres(我没有的MySQL在这里,所以也许这是不同的一点点):

select matches.id, 
     (matches.tfirstname 
     + matches.tlastname 
     + matches.tschool 
     + matches.tcollege 
     + matches.tuniversity) as total 
from (
    select u.id, 
      (case when u.firstname like '%a%' then 1 else 0 end) as tfirstname, 
      (case when u.lastname like '%b%' then 1 else 0 end) as tlastname, 
      sum(e2.nschool) as tschool, 
      sum(e2.ncollege) as tcollege, 
      sum(e2.nuniversity) as tuniversity 
    from tbluser u left outer join (
     select e.usr, 
      (case when e.school like '%c%' then 1 else 0 end) as nschool, 
      (case when e.college like '%d%' then 1 else 0 end) as ncollege, 
      (case when e.university like '%e%' then 1 else 0 end) as nuniversity 
     from tbleduc e 
    ) e2 on u.id=e2.usr 
    group by u.id, u.firstname, u.lastname 
) as matches 

我用这些DDL语句来创建表:

create table tbluser (
    id int primary key, 
    firstname varchar(255), 
    lastname varchar(255) 
) 


create table tbleduc (
    id int primary key, 
    usr int references tbluser, 
    school varchar(255), 
    college varchar(255), 
    university varchar(255) 
) 

和示例性数据的一点点:

insert into tbluser(id, firstname, lastname) 
      values (1, 'Jason', 'Bourne'); 
insert into tbleduc(id, usr, school, college, university) 
      values (1, 1, 'SomeSchool', 'SomeCollege', 'SomeUniversity'); 
insert into tbleduc(id, usr, school, college, university) 
      values (2, 1, 'MoreSchool', 'MoreCollege', 'MoreUniversity'); 

查询可以简化一个位,如果相对tblusertbleduc之间的关系是1:1。

不要忘记用你的变量替换%a%%b,...(我建议使用准备好的语句)。

我希望这个模板帮助作为一个基本的解决方案 - 你可以调整它,就像你喜欢:-)你也可以去除最外面的SELECT语句,以获得个人成绩的计数器。

1

第1步:定义一个计算“相关性”的方法。

步骤2:收件其使用来自步骤1的计算,以确定其结果的顺序的查询。

不幸的是,你还没有说是什么让一个记录“更相关”或比另一种“不太相关”,所以这大约相当于我们可以在这一点告诉你。

+0

相关性先由更多匹配项计算。比如像'name','school'和'college'这样的搜索词应该出现在与'name'和'school'匹配的字段的顶部 – 2010-03-13 11:51:44

0

你有足够的时间和资源来尝试实现Solr?相关度排名搜索的效果要好得多,而且开始使用起来也非常容易。

1

你有没有尝试过的比赛 - 你的桌子上反对的查询。结果集按相关性默认排序。另外它做全文搜索。