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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章