2016-11-21 58 views
0
中找到類似的和獨特的喜好

假設我們有兩個表如下:MYSQL:朋友

  1. 朋友(UID1 INT,UID2 INT)

    此表持有的所有ID的彼此都是朋友的人。

  2. 喜歡(UID,LID)

    此表包含的項目由每個用戶ID喜歡(由蓋指數)

我想知道的,每個朋友A和B,他們都喜歡多少物品,以及他們喜歡的多少獨特物品。

我正在使用MySQL,所以我們沒有完全加入。

這看起來像這樣一個複雜的查詢給我。我覺得我得到了一些點來獲得一些值,但我想知道別人怎麼會做這樣的:

下面是代碼來構建示例表爲朋友喜歡

create table friend (uid1 int, uid2 int); 

insert into friend values 
(1,2), 
(2,1), 
(1,3), 
(2,3); 

create table likes(uid int, lid int); 

insert into likes values 
(1, 2), 
(1, 3), 
(1, 4), 
(2, 1), 
(2, 2), 
(3, 5), 
(3, 4); 

這裏是到目前爲止我的執行:

select r.uid1, r.uid2, 
    sum(case when r.lid1 is null then 0 else 1 end) as uniqueLike1, 
    sum(case when r.lid2 is null then 0 else 1 end) as uniqueLike2, 
    sum(case when r.lid1 is not null and r.lid2 is not null then 1 else 0 end) as uniqueLike1and2 
from 
(select f.uid1 as uid1, f.uid2 as uid2, l1.lid as lid1, l2.lid as lid2 
from friend f join likes l1 on f.uid1 = l1.uid left join likes l2 on f.uid2=l2.uid and l1.lid = l2.lid 
union 
select ff.uid1 as uid1, ff.uid2 as uid2, ll2.lid as lid1, ll1.lid as lid2 
from friend ff join likes ll1 on ff.uid2 = ll1.uid left join likes ll2 on ff.uid1=ll2.uid and ll1.lid = ll2.lid) r 
group by r.uid1, r.uid2; 

回答

0

這不是一個傳統的做法。我甚至不希望它是有效的(特別是如果用戶喜歡很多東西)。但是,它具有相對簡單的優點:

select f.uid1, f.uid2, 
     count(distinct case when l1.lid = l2.lid then l1.lid end) as likes_in_common, 
     (count(distinct l1.lid) - 
     count(distinct case when l1.lid = l2.lid then l1.lid end) 
     ) as likes_only1, 
     (count(distinct l2.lid) - 
     count(distinct case when l1.lid = l2.lid then l1.lid end) 
     ) as likes_only2 
from friend f left join 
    likes l1 
    on l1.uid = f.uid1 left join 
    likes l2 
    on l2.uid = f.uid2 
group by f.uid1, f.uid2; 

這個想法是計算共同項目的數量。這是第一個count()表達式。然後,通過減法給出唯一的。

COUNT(DISTINCT)是必需的,因爲FROM子句爲兩個用戶生成所有喜歡的笛卡爾積。