5

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

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

此查询显示朋友的朋友和我的朋友,并且相互计数也不正确。我试过的查询。

4

1 回答 1

1

RAND()MySQL 中的函数返回一个随机浮点值,您还可以像这样以随机顺序检索行:

   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在调试此类复杂查询时非常有用。

更多信息:

于 2013-05-26T14:28:34.980 回答