在数学公式中,我想计算差异或相似度,差异等于sqrt(s1 - t1)^2
,因此种子行Value1
与比较Value1
之差的平方根排,平方。 S1
等于种子行的value1
,T1
等于比较行的value1
。
计算种子行与比较行的总体相似性或差异:
[sqrt(s1-t1)^2]+[sqrt(s2-t2)^2]+[sqrt(s3-t3)^2]+... = Similarity
因此,例如,使用下表,ID1
是种子行,Id2
是比较行,然后ID3
,然后是id4
,依此类推是以下比较行。
[sqrt(3-1)^2]+[sqrt(4-5)^2]+[sqrt(3-3)^2]+[sqrt(5-5)^2]+[sqrt(0-4)^2]+[sqrt(1-1)^2]
+[sqrt(3-2)^2]+[sqrt(4-4)^2] = 2 + 1 + 0 + 0 + 4 + 0 +1 + 4 = 12
列表,
ID1 to ID2: 2 + 1 + 0 + 0 + 4 + 0 + 1 + 4 = 12
ID1 to ID3: 1 + 1 + 1 + 4 + 4 + 0 + 2 + 1 = 14
ID1 to ID4: 0 + 0 + 0 + 3 + 1 + 1 + 0 + 1 = 6
ID1 to ID5: 1 + 0 + 0 + 4 + 0 + 4 + 3 + 3 = 15
因此,根据该公式,已确定行ID4
与行ID1
最匹配,因为它的编号最小。
ID | Value1 | Value2 | Value3 | Value4 | Value5 | Value6 | Value7 | Value8 |
----------------------------------------------------------------------------------
1 | 3 | 4 | 3 | 5 | 0 | 1 | 3 | 4 |
2 | 1 | 5 | 3 | 5 | 4 | 1 | 2 | 4 |
3 | 4 | 3 | 2 | 1 | 4 | 1 | 1 | 5 |
4 | 3 | 4 | 3 | 2 | 1 | 2 | 3 | 3 |
5 | 2 | 4 | 3 | 1 | 0 | 5 | 0 | 1 |
我正在使用PHP和MySQL,我想知道如何实现上述解释?
答案 0 :(得分:1)
为了找到最接近特定行的行,您可以使用这样的查询, 其中每一行都连接到种子行,结果按计算的差异排序:
SELECT t2.*, ABS(t1.v1-t2.v1)+ABS(t1.v2-t2.v2)+ABS(t1.v3-t2.v3) AS diff
FROM (SELECT * FROM tbl WHERE id=1) AS t1
JOIN tbl AS t2 ON t1.id <> t2.id
ORDER BY diff;
如果要查找每对行之间的差异,可以执行以下查询:
SELECT t1.id AS t1_id, t2.id AS t2_id,
ABS(t1.v1-t2.v1)+ABS(t1.v2-t2.v2)+ABS(t1.v3-t2.v3) AS diff
FROM tbl AS t1
INNER JOIN tbl AS t2 ON t1.id <> t2.id
ORDER BY t1.id, diff;