[英]How to compare rows of the same table and apply a weight from another table to each column
我正在嘗試在 MySQL 中構建一種“個人”匹配數據庫。
我需要將成員表中的特定人員與同一表中的所有其他人進行比較。
表中的每一行(人)都有許多列,其中包含他們的信息(年齡、位置、宗教等)。
我需要查詢來引用一個表,該表包含我的每一列的“權重”。 換句話說,我想說“75歲時位置很重要,100歲時年齡范圍非常重要,而10歲時宗教不重要”。
成員表
+----+-------+----------+----------+-----+----------+
| ID | Name | Location | Religion | Age | AgeRange |
+----+-------+----------+----------+-----+----------+
| 1 | Joe | LA | Athiest | 40 | 30-40 |
+----+-------+----------+----------+-----+----------+
| 2 | Mary | LA | Agnostic | 35 | 35-45 |
+----+-------+----------+----------+-----+----------+
| 3 | Karen | NYC | Athiest | 45 | 30-35 |
+----+-------+----------+----------+-----+----------+
| 4 | Lisa | LA | Hindu | 30 | 45-55 |
+----+-------+----------+----------+-----+----------+
權重表(參數的重要性)
+----+-----+----------+----------+
| ID | Age | Location | Religion |
+----+-----+----------+----------+
| 1 | 100 | 75 | 10 |
+----+-----+----------+----------+
在過去的 2 天里,我嘗試了很多東西,但我嘗試使用的最新查詢是這個,這顯然沒有多大用處。 它也沒有指定將與這些記錄進行比較的“人”。
SELECT a.first_name,
g.name,
a.age* g.age+
a.location* g.location+
a.religion * g.mwReligion AS metric
FROM members a, weight g
ORDER BY metric DESC;
我的預期輸出是這樣的:
喬比賽:
瑪麗 - 分數 = 285
(100 因為她在他的年齡范圍內 + 100 因為他在她的年齡范圍內 + 75 代表位置 + 10 代表宗教)
麗莎 - 分數 = 175(100 因為她在他的年齡范圍內 + 75 位置)
凱倫 - 分數 = 10(僅宗教匹配)
我假設min_age
和max_age
列是分開的(而不是AgeRange
),包括在內,並且是INT
數據類型。 您需要的查詢應如下所示:
select
x.id,
x.name,
x.ma as match_age,
x.ml as match_location,
x.mr as match_religion,
x.ma * w.age + x.ml * w.location + x.mr * w.religion as total_score
from (
select
o.id,
o.name,
case when o.age between p.min_age and p.max_age then 1 else 0 end as ma,
case when o.location = p.location then 1 else 0 end as ml,
case when o.religion = p.religion then 1 else 0 end as mr
from (select * from members where id = 1) p -- selects Joe
cross join (select * from members where id <> 1) o -- select other members
) x
cross join weights w
在 MySQL 中,布爾表達式在數字上下文中變為 0 或 1。 所以你可以使用你的比較作為因素。
因此,self 將成員的 id 加入到比其他成員低的成員中(否則,即在檢查不等式時,結果中每對都有兩次)。 然后交叉加入權重。
現在,您可以將指標構建為比較和權重的乘積之和。
我假設宗教和比較是通過平等來比較的。 一個人的年齡與另一個人的年齡范圍進行比較,反之亦然。 此外,我將年齡范圍分為下限和上限,並假設該范圍的界限是包含在內的。 那么這可能如下所示:
SELECT m1.name,
m2.name,
(m1.age BETWEEN m2.agerangelower
AND m2.agerangeupper) * w1.age
+
(m2.age BETWEEN m1.agerangelower
AND m1.agerangeupper) * w1.age
+
(m1.location = m2.location) * w1.location
+
(m1.religion = m2.religion) * w1.religion metric
FROM members m1
INNER JOIN members m2
ON m1.id < m2.id
CROSS JOIN weights w1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.