我有两张桌子:
朋友表格(UserID
,FriendID
)和
用户表(UserID
,FirstName
,LastName
)。
我正在尝试执行一个SQL查询来加入并提取所有记录,其中的朋友表中的UserID
或FriendID
等于用户的ID,但请提取FirstName
和{来自其他LastName
的{1}}。
例如
朋友表
UserID
用户表
UserID = 1 | FriendID = 2
UserID = 3 | FriendID = 1
如果我以Bob(UserID = 1 | FirstName = "Bob" | LastName = "Hope"
UserID = 2 | FirstName = "John" | LastName = "Doe"
UserID = 3 | FirstName = "Bill" | LastName = "Murray"
= 1)的身份登录,尝试通过检查{{1}来在一个查询中提取所有朋友的用户数据(UserID
和FirstName
)在Friends表中,1是LastName
或UserID
。然后加入不是我的ID的相反字段的数据。
有什么想法吗?
答案 0 :(得分:1)
-- 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
UserID FirstName LastName
2 John Doe
1 Bob Hope
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');
答案 1 :(得分:1)
试试这个:
SELECT *
FROM users u
WHERE userid IN ( SELECT userid FROM friends WHERE friendid = 1
UNION ALL
SELECT friendid FROM firends WHERE userid = 1);
这会给你:
| USERID | FIRSTNAME | LASTNAME |
---------------------------------
| 2 | John | Doe |
| 3 | Bill | Murray |
答案 2 :(得分:1)
Select b.uid as userid, a.firstname, a.lastname
from user a
Inner join (select friendid as uid from friends where userid=:currentUser
Union select userid as uid from friends where friendid=:currentUser) b
在手机上,可能需要进行语法调整。
优化工具可能会根据您的实际数据建议不同的加入策略