SQL求相互关注的人数和关注了4的总关注数

求互相关注的人数?

select count(1) from tst t1
inner join tst t2
on t1.uid = t2.uuid and t1.uuid = t2.uid;

求关注了4的总关注数?

select count(1) from tst t1
inner join (select uid from tst where uuid = '4') t2
on t1.uid = t2.uid;

 

select t1.* from tst t1
inner join (select a,b from tst ) t2
on t1.b = t2.a and t1.a = t2.b

-- ----------------------------

-- Table structure for `tst`
-- ----------------------------
DROP TABLE IF EXISTS `tst`;
CREATE TABLE `tst` (
`uid` int(10) NOT NULL,
`uuid` int(10) NOT NULL,
`desc` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


-- ----------------------------
-- Records of tst
-- ----------------------------
INSERT INTO `tst` VALUES ('1', '2', null);
INSERT INTO `tst` VALUES ('1', '3', null);
INSERT INTO `tst` VALUES ('1', '4', null);
INSERT INTO `tst` VALUES ('2', '5', null);
INSERT INTO `tst` VALUES ('2', '1', null);
INSERT INTO `tst` VALUES ('3', '4', null);
INSERT INTO `tst` VALUES ('3', '1', null);
INSERT INTO `tst` VALUES ('5', '4', null);
INSERT INTO `tst` VALUES ('5', '6', null);
INSERT INTO `tst` VALUES ('5', '1', null);

 

------不用join的方法---------

 

select c1,c2 from(
select a c1,b c2 from table
union all 
select b c1,a c2 from table 
) t
group by c1,c2
having count(1) > 1

你可能感兴趣的:(SQL求相互关注的人数和关注了4的总关注数)