我正在尝试编写一个像这样工作的朋友系统:
这是我的数据库结构:
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(16) NOT NULL, `password` char(32) NOT NULL, `email` varchar(80) NOT NULL, `dname` varchar(24) NOT NULL, `profile_img` varchar(255) NOT NULL DEFAULT '/images/default_user.png', `created` int(11) NOT NULL, `updated` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`), UNIQUE KEY `username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
CREATE TABLE IF NOT EXISTS `friend_requests` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_a` int(11) NOT NULL DEFAULT '0', `user_b` int(11) NOT NULL DEFAULT '0', `viewed` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
CREATE TABLE IF NOT EXISTS `friends` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_a` int(11) NOT NULL DEFAULT '0', `user_b` int(11) NOT NULL DEFAULT '0', `friend_type` int(3) NOT NULL DEFAULT '1', `friends_since` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
我可以使用“SELECT * FROM friends WHERE user_a = $ userid OR user_b = $ userID”列出用户朋友,但如何从{{username
或profile_img
获取数据1}}表?
答案 0 :(得分:9)
我认为你有点过分(!)你的问题。
您可以只拥有一个User
表和一个Friendship
表。您的友谊表可能包含UserID int, FriendID int, Created_at datetime, Confirmed_at datetime
。
<击> 撞击>
select * from User
left outer join Friendship on User.ID = Friendship.UserID
left outer join User as Friend on Friendship.FriendID = Friend.ID
where User.ID = <some users ID>
击> <击> 撞击> 编辑:我可能第一次亲自过度使用它;)
select * from Friendship
inner join User on Friendship.FriendID = User.ID
where Friendship.UserID = <some users ID>
这会吸引用户朋友...... (MSSQL语法)
哦,我忘了。当Confirmed_at
为null
时,友情请求尚未确认。
答案 1 :(得分:2)
SELECT DISTINCT
a.username,
a.profile_img
FROM
users a
WHERE
a.id in (SELECT user_a FROM friends WHERE user_a = $userid OR user_b = $userID)
and a.id <> $userid
UNION
SELECT
b.username,
b.profile_img
FROM
users b
WHERE
b.id in (SELECT user_b FROM friends WHERE user_a = $userid OR user_b = $userID)
and b.id <> $userid
答案 2 :(得分:0)
您需要使用联接将表朋友加入用户。 例如:
SELECT * FROM friends as f INNER JOIN users AS u ON u.id = f.user_a WHERE user_a = $userid