0

我的 mysql 查询有问题,无法以任何方式完成。我已经检查了其他主题,但在我的情况下无法获得任何解决方案。

我有两张桌子,一张是用户

id, name, email....

第二个朋友被命名为朋友:)

user1_id, user2_id

现在我需要从数据库中获取我朋友的朋友的所有用户信息,以及下一级朋友,我的朋友的朋友的朋友,这些应该是 2 个单独的查询。当然,搜索应该排除我,并且是不同的。

4

1 回答 1

0

应该这样StoredProcedure

CREATE PROCEDURE `friend_list`(user_id INT, MaxLevel INT)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN

DECLARE LLevel, LCount INT DEFAULT 0;

DROP TABLE IF EXISTS tmp_friends;

CREATE TEMPORARY TABLE tmp_friends
    SELECT user1_id AS friend_id, LLevel AS friend_level
        FROM friends
        WHERE user2_id = user_id
    UNION
    SELECT user2_id, LLevel
        FROM friends
        WHERE user1_id = user_id;

SELECT COUNT(*) INTO LCount FROM tmp_friends;

DROP TABLE IF EXISTS tmp_fr;

WHILE ( LCount > 0 ) AND ( LLevel < MaxLevel ) DO

    SET LLevel = LLevel + 1;

    CREATE TEMPORARY TABLE tmp_fr
        SELECT user1_id as friend_id, LLevel as friend_level
        FROM friends
        WHERE user2_id IN ( SELECT friend_id FROM tmp_friends WHERE friend_level = LLevel - 1 );

    INSERT INTO tmp_fr
        SELECT user2_id as friend_id, LLevel as friend_level
        FROM friends
        WHERE user1_id IN ( SELECT friend_id FROM tmp_friends WHERE friend_level = LLevel - 1 );

    DELETE FROM tmp_fr 
    WHERE friend_id IN ( SELECT friend_id FROM tmp_friends ) 
       OR friend_id = user_id;

    SELECT COUNT(*) INTO LCount FROM tmp_fr;

    INSERT INTO tmp_friends
        SELECT * FROM tmp_fr;

    DROP TABLE tmp_fr;

END WHILE;

SELECT * 
FROM tmp_friends 
ORDER BY friend_level;

DROP TABLE tmp_friends;

END

您将获得一个包含id用户和朋友级别的结果集(0 是直接的,1 是朋友的朋友,...)。

你只需要传递 user_id 和最大的friendlevel

CALL friend_list( 1, 10 );

我使用了这个表结构

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `friends` (
  `user1_id` int(11) unsigned NOT NULL,
  `user2_id` int(11) unsigned NOT NULL,
  PRIMARY KEY (`user1_id`,`user2_id`),
  KEY `fk_friends_users2` (`user2_id`),
  CONSTRAINT `fk_friends_users2` FOREIGN KEY (`user2_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_friends_users1` FOREIGN KEY (`user1_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
于 2012-12-16T11:02:42.567 回答