Navicat SQL - 找出互赞的用户

题目

id1是用户id,id2是被点赞用户id

#建立活跃表
create table LikeTable( 
id1 varchar(20) not null, 
id2 varchar(20))
ENGINE=InnoDB DEFAULT CHARSET=utf8;
#插入活跃数据
INSERT INTO LikeTable 
(id1, id2) 
VALUES 
('a','b'),
('a', 'c'),
('a' ,'d'),
('b', 'a'),
('b', 'c'),
('b', 'd'),
('b', 'e'),
('c', 'a'),
('c', 'f'),
('c', 'b'),
('e', 'a'),
('e', 'b'),
('a', 'f'); 
select t1.id1 as id1,t1.id2 as id2,t2.id2 as id3
from
(select id1,id2 from LikeTable) t1
inner join 
(select id1,id2 from LikeTable) t2
on t1.id2 = t2.id1
where t1.id1 = t2.id2

b a b
c a c
a b a
c b c
e b e
a c a
b c b
b e b

-- 互相点过赞的用户
select t1.id1 as id1,t1.id2 as id2
from
(select id1,id2 from LikeTable) t1
inner join 
(select id1,id2 from LikeTable) t2
on t1.id2 = t2.id1
where t1.id1 = t2.id2

b a
c a
a b
c b
e b
a c
b c
b e

-- 参与过互赞的去重用户
select distinct t1.id1 as id1
from
(select id1,id2 from LikeTable) t1
inner join 
(select id1,id2 from LikeTable) t2
on t1.id2 = t2.id1
where t1.id1 = t2.id2

优化

会出现ab互赞,ba互赞这种业务逻辑上其实是重复的情况

select t1.id1 as id1,t1.id2 as id2,t2.id2 as id3,t2.id1 as id4
from
(select id1,id2 from LikeTable) t1
inner join 
(select id1,id2 from LikeTable) t2
on t1.id2 = t2.id1
where t1.id1 = t2.id2
and t1.id2 not in t2.id1

错误答案

在这里插入图片描述

select distinct * from
(select id1 from LikeTable) t1
inner join 
(select id2 from LikeTable) t2
on t1.id1 = t2.id2

b b
c c
a a
e e

Tips1

点赞数据库设计 : https://bbs.csdn.net/topics/391001223

Tips2

快手面经

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值