如果我理解你的问题,那么这有效
-- set the id of the logged in user
set @logged_in = 1;
-- select all the fields from the user table
select users.* from users
-- joined the friends table on the `FriendID`
inner join friends on friends.FriendID = users.UserID
-- filtered by `UserID` on friends table matching logged in user
and friends.UserID = @logged_in -- logged in id
-- union-ed with the users table
union select * from users
-- filtered by the `UserID` being the logged in user
where users.UserID = @logged_in -- logged in id
@logged_in = 1 的结果:
UserID FirstName LastName
2 John Doe
1 Bob Hope
@logged_in = 2 的结果:
UserID FirstName LastName
2 John Doe
测试数据库创建代码:
--
-- Table structure for table `friends`
--
CREATE TABLE IF NOT EXISTS `friends` (
`UserID` int(11) NOT NULL,
`FriendID` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `friends`
--
INSERT INTO `friends` (`UserID`, `FriendID`) VALUES
(1, 2),
(3, 1);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`UserID` int(11) NOT NULL,
`FirstName` varchar(50) NOT NULL,
`LastName` varchar(50) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`UserID`, `FirstName`, `LastName`) VALUES
(1, 'Bob', 'Hope'),
(2, 'John', 'Doe'),
(3, 'Bill', 'Murray');