好吧,我想這對你的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');
查詢可以簡化一個位,如果相對tbluser
和tbleduc
之間的關係是1:1。
不要忘記用你的變量替換%a%
,%b
,...(我建議使用準備好的語句)。
我希望這個模板幫助作爲一個基本的解決方案 - 你可以調整它,就像你喜歡:-)你也可以去除最外面的SELECT語句,以獲得個人成績的計數器。
相關性先由更多匹配項計算。比如像'name','school'和'college'這樣的搜索詞應該出現在與'name'和'school'匹配的字段的頂部 – 2010-03-13 11:51:44