わかりました、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 ステートメントを削除することもできます。