You could do it like this:
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
parent_id int(11) NOT NULL DEFAULT '0',
user_name varchar(32),
.... more columns ...
);
and insert some data here:
INSERT INTO users VALUES (1,0,'User1');
INSERT INTO users VALUES (2,0,'User2');
INSERT INTO users VALUES (3,1,'User1_1');
INSERT INTO users VALUES (4,1,'User1_2');
INSERT INTO users VALUES (5,4,'User1_2_1');...
And create a function like:
CREATE FUNCTION f_get_top_user_id (xusers_id INT)
RETURNS text
DETERMINISTIC
BEGIN
DECLARE xtop_id int;
DECLARE xparent_id int;
SELECT u.parent_id INTO xparent_id FROM users u WHERE u.id = xusers_id;
SELECT u.id INTO xtop_id FROM users u WHERE u.id = xusers_id;
WHILE (xparent_id > 0) DO
BEGIN
SELECT u.id INTO xtop_id FROM users u WHERE u.id = xparent_id;
SELECT u.parent_id INTO xparent_id FROM users u WHERE u.id = xparent_id;
END;
END WHILE;
RETURN xtop_id;
END
And if you call that function like
SELECT f_get_top_user_id(5);
it should return 1 (User1)