0
中找到類似的和獨特的喜好
假設我們有兩個表如下:MYSQL:朋友
朋友(UID1 INT,UID2 INT)
此表持有的所有ID的彼此都是朋友的人。
喜歡(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;