得到朋友的随机朋友相互计数

时间:2013-05-26 08:16:15

标签: mysql

我有一个用户和一个朋友表。具有用户详细信息的用户和朋友拥有用户的朋友。这是用户表的架构..

create table smsusers(
  id varchar(60),
  password varchar(50) not null,
  fname varchar(30) not null,
  lname varchar(30),
  mailid varchar(50) not null,
  gender varchar(10) not null,
  primary key(id)
);

和朋友表..

create table friends_list(
  friend_of varchar(60) NOT NULL,
  friends_id varchar(60) NOT NULL,
  friendship_status varchar(30),
  friendship_date timestamp NOT NULL,
  primary key(friend_of,friends_id),
  foreign key(friend_of) references smsusers(id)
  ON DELETE CASCADE ON UPDATE CASCADE);

个人资料照片

create table profile_pic(pic_id varchar(200),profile_pic_path varchar(1000),small_pic_path varchar(1000),
adddate varchar(100),userid varchar(60),foreign key(userid) references smsusers(id) ON DELETE CASCADE ON UPDATE CASCADE,
primary key(pic_id));

在这里,我想以共同朋友计数的方式随机抽取5位朋友

我试过了这个查询

SELECT DISTINCT ff.friends_id,
   concat(u.fname,' ',u.lname),
   pp.small_pic_path,
   count(*) AS mutual_friend_count
    FROM
    friends_list f
    JOIN friends_list ff
    ON ff.friend_of =f.friends_id
    LEFT JOIN smsusers u
    ON
    u.id=ff.friends_id
    LEFT JOIN profile_pic pp
    ON
    ff.friends_id=pp.userid
    WHERE f.friend_of = 1
    AND ff.friends_id NOT IN (1)
GROUP BY friends_id

此查询显示朋友的朋友以及我的朋友,并且相互计数也不正确。 查询我tried

1 个答案:

答案 0 :(得分:1)

MySQL中的

RAND()函数返回一个随机浮点值,你也可以按照随机顺序检索行:

   SELECT * 
     FROM tbl_name 
 ORDER BY RAND();

重新编写查询以显示每个用户的朋友及其计数,随机选择:

   SELECT DISTINCT u.id,
          CONCAT(u.fname,' ',u.lname) AS 'User',
          GROUP_CONCAT(CONCAT(f.fname,' ',f.lname) SEPARATOR ', ') AS 'Friends',
          COUNT(*) AS mutual_friend_count
     FROM smsusers u
     JOIN friends_list ff
       ON u.id = ff.friends_id
     JOIN smsusers f
       ON ff.friend_of = f.id
  --WHERE u.id = 1
 GROUP BY friends_id
 ORDER BY RAND()
    LIMIT 5;

如果您使用WHERE子句,查询将输出用户Manish Sahu的朋友。

修改

另一种实现方法是创建VIEW

   CREATE VIEW facebook AS
   SELECT u.id,
          CONCAT(u.fname,' ',u.lname) AS 'User',
          ff.friend_of
     FROM smsusers u
     JOIN friends_list ff
       ON u.id = ff.friends_id
     JOIN smsusers f
       ON ff.friend_of = f.id;

然后,使用我们新生成的VIEW

重写第一个查询
   SELECT f.*,
          GROUP_CONCAT(friend_of SEPARATOR ', ') AS 'FriendsIDs',
          COUNT(*) AS mutual_friend_count
     FROM facebook f
 GROUP BY id
 ORDER BY RAND()
    LIMIT 5;

然后,您还可以检索随机生成的用户朋友列表:

   SELECT f.*,
          (SELECT `User` 
             FROM `facebook` 
            WHERE `friend_of` IN (1)
         ORDER BY RAND()
            LIMIT 1) AS 'RandomFriends'
     FROM facebook f
    WHERE id = 1;

此外,函数GROUP_CONCAT在调试此类复杂查询时非常有用。

更多信息: