我正在尝试建立一个类似Facebook的搜索好友系统,但是结果有问题。结果未显示给好友,它将两次显示所有数据。
我进行了以下查询:
$uid = '1';
$key = 'john'
$result = mysqli_query($this->db,"
SELECT U.username,U.userid,U.userfullname, F.userone, F.usertwo, F.role
FROM users U, friends F WHERE U.username like '%$key' OR
U.userfullname like '$key%' OR U.username like '$key%' OR
U.userfullname like '%$key' OR U.username like '$key' OR
U.userfullname like '$key' AND F.userone=U.userid AND
F.userone='$uid' AND F.role='fri' AND F.userone = '$uid'
ORDER BY F.userone = '$uid' LIMIT 10") or die(mysqli_error($this->db));
用户数据表,
CREATE TABLE `users` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`userfullname` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`userstatus` enum('0','1','2') NOT NULL DEFAULT '0',
PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `users` (`userid`, `username`, `userfullname`,`userstatus`) VALUES
(1, 'john', 'John Doe', '0'),
(2, 'aziz', 'aziz', '0'),
(3, 'selma', 'Selma Kose', '0');
朋友表
CREATE TABLE `friends` (
`friendid` int(11) NOT NULL AUTO_INCREMENT,
`userone` int(11) DEFAULT NULL,
`usertwo` int(11) DEFAULT NULL,
`role` enum('flwr','fri') NOT NULL DEFAULT '1',
PRIMARY KEY (`friendid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
INSERT INTO `friends` (`friendid`, `userone`, `usertwo`, `role`) VALUES
(1, 1, 1, 'me'),
(2, 2, 2, 'me'),
(3, 3, 3, 'me'),
(4, 2, 1, 'fri'),
(5, 2, 3, 'flwr'),
(6, 3, 1, 'fri');
请以为您正在搜索朋友,并且用户ID为1,并且正在搜索方位角。如果是,则查询查询方位角是您的朋友(fri or flwr
),然后显示结果。但是我的查询显示所有用户而不仅仅是朋友。
我在这里缺少什么,在这方面有人可以帮助我吗?
结果必须仅为john用户名,但显示所有用户两次。
这里是 DEMO
答案 0 :(得分:1)
尝试此查询:
SELECT U.username userone, UT.username usertwo, F.role FROM friends F
JOIN users U ON F.userone = U.userid
JOIN users UT ON F.usertwo = UT.userid
WHERE
UT.username = 'john' AND F.userone = 1
AND (F.role = 'fri' OR F.role = 'flwr')
它将返回id = 2(名称为john
)的所有用户朋友。