![](/img/trans.png)
[英]Fetch two rows of different values of the same column from database (MySQL)
[英]MySQL - Get similarity score from where two different rows meet same condition from two columns
我想做的是通過將一個表中的評級列與另一表中的評級列進行比較來生成相似度百分比量。
但是,這需要限於一個表中的ID與另一表中的ID匹配,針對特定用戶且兩個表的評級列中都存在評級的實例。
例如,表1具有以下列和數據:
id | rate (out of 10)
=====================
1 | 8
2 | 10
3 | 5
4 | 4
5 | 0
6 | 9
7 | 8
並且table2具有以下列和數據:
movid | userid | rating (out of 10)
================================
1 | 3 | 6
2 | 2 | 10
3 | 1 | 4
4 | 3 | 7
5 | 3 | 6
6 | 4 | 8
7 | 3 | 5
因此,可以說我想使用“ userid” = 3的任何行,並將它們從table2的“ rating”與table1的“ rate”列進行比較,其中“ rate”> 0且兩個表的id / movid具有相同的編號。
使用上面的示例,要比較的結果應限於:
id | rate
=====================
1 | 8
4 | 4
7 | 8
movid | userid | rating
================================
1 | 3 | 6
4 | 3 | 7
7 | 3 | 5
即使userid 3在表 2中對Movid 5的評分為0,但在表 1中對ID 5的評分為0(無評分),因此不會進行比較。
這將比較每個id / movid的收視率,然后將其總計。 由於評分數字基於10分,因此我猜想確定相似度百分比的最佳方法是將每個id / movid之間的差值減去10,得出百分比數。
用於ID / movid 1, 表1中的“速率”是8和表2中 “等級”是6。這些數字之間的差是2。我們從10減去2,以獲得80%的相似性得分為ID / movid 1。
每次比較都需要進行該操作,然后將其總計。
因此,根據我的計算,id / movid 1、4和7的總和的相似度得分將為73%(四舍五入不帶小數)。
這個總百分比是我試圖達到的最終結果。 誰能幫我嗎? 在拔出所有頭發以使其正常工作之后,我現在禿頂。
我想您正在尋找的是:
SEELCT table1.id, table1.rate, table2.rating
FROM table1 INNER JOIN table2 ON table1.id=table2.movid
WHERE table1.rate>0 AND table2.userid=3
一個簡單的INNER join加where子句中的過濾器可以過濾userid = 3並顯示大於零的比率
以下不是最佳解決方案,但它應該可以工作:
select ROUND(sum(tmp.similarity_score)/max(tmp.cnt)) as Total_similarity_score
from
(
select t1.id,t1.rate,t2.movid,t2.rating,
(10 - abs(t1.rate-t2.rating))*10 as similarity_score,
(@cnt := @cnt +1) as cnt
from t1
inner join t2
on t2.movid = t1.id
cross join (select @cnt := 0)r
where userid = 3
and t1.rate <> 0
)tmp
;
SELECT ROUND(SUM(10-ABS(table1.rate-table2.rating))*10/count(table1.id)) as per FROM table1 INNER JOIN table2 ON table1.id=table2.movieid WHERE userid=3 and table1.rate <> 0 GROUP BY userid
這將為您提供所需的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.