目前有一用户数据表,用于记录用户关系,结构如下:
CREATE TABLE `rel` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `uid1` int(10) unsigned NOT NULL COMMENT '前者uid',
 `uid2` int(10) unsigned NOT NULL COMMENT '后者uid',
 `rel` int(1) NOT NULL COMMENT '用户关系,0为uid1关注uid2,1为互相关注,-1为uid1拉黑uid2,-2为双向拉黑',
 `time` int(10) unsigned NOT NULL COMMENT '时间',
 PRIMARY KEY (`id`),
 KEY `uid1` (`uid1`),
 KEY `uid2` (`uid2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户关系表'
还有一用户表,结构如下:
CREATE TABLE `user` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `username` char(32) NOT NULL COMMENT '用户名',
 `password` char(32) NOT NULL COMMENT '密码',
 `email` char(64) NOT NULL COMMENT '邮箱',
 `time` int(11) unsigned NOT NULL COMMENT '注册时间',
 PRIMARY KEY (`id`),
 UNIQUE KEY `username` (`username`),
 KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表'
其中 rel 表的 uid1、uid2 都对应 user 表的 id。
现在需要查出某一用户的关注列表,返回每一条记录需要包含:被关注人的UID,被关注人的用户名、被关注人的关注数、被关注人的粉丝数、被关注人是否与本人互相关注。
下面是我现有的一条SQL语句(以下语句中 {$uid} 表示要查询关注列表的用户UID):
SELECT IF(rel.uid1={$uid},rel.uid2,rel.uid1) AS uid, user.username, rel.rel, rel.time, IF(rel.rel=1,1,0) AS is_friend
FROM rel
LEFT JOIN user ON IF(rel.uid1={$uid},rel.uid2,rel.uid1)=user.id
WHERE (rel.uid1={$uid} AND (rel.rel=0 OR rel.rel=1)) OR (rel.uid2={$uid} AND rel.rel=1)
但该语句只是查询出了用户的关注列表和用户关注的人是否与本人为互粉关系,并没有查出关注的每一个人的关注数与粉丝数。
求各位菊苣们写一条SQL语句实现查询该用户的关注列表中的每一个用户的关注数与粉丝数。谢谢!

解决方案 »

  1.   

    drop temporary table if exists tmp_result;
    create temporary table if not exists tmp_result(uid int,username varchar(32),flag tinyint)engine=heap; #flag 0:单向关注 1:双向关注drop temporary table if exists tmp_gznum;
    create temporary table if not exists tmp_gznum(uid int,gznum int)engine=heap;drop temporary table if exists tmp_fsnum;
    create temporary table if not exists tmp_fsnum(uid int,fsnum int)engine=heap;insert into tmp_result(uid,username,flag)
    select a.uid2,b.username,a.rel
    from rel a
    inner join user b on a.uid2=b.id
    where a.uid1=1 and (rel=0 or rel=1);insert into tmp_gznum(uid,gznum)
    select a.uid,count(b.uid2) as gznum
    from tmp_result a
    inner join rel b on a.uid=b.uid1
    where b.rel=0 or b.rel=1
    group by a.uid;insert into tmp_fsnum(uid,fsnum)
    select a.uid,count(b.uid1) as fsnum
    from tmp_resul a
    inner join rel b on a.uid=b.uid2
    where b.rel=0 or b.rel=1
    group by a.uid;select a.uid,a.username,ifnull(b.gzname,0) as gznum,ifnull(b.fsnum,0) as fsnum,a.flag
    from tmp_result a
    left join tmp_gznum b on a.uid=b.uid
    left join tmp_fsnum c on a.uid=c.uid;drop temporary table if exists tmp_result;
    drop temporary table if exists tmp_gznum;
    drop temporary table if exists tmp_fsnum;可以实现功能,但是性能有待提高