0

我有两张桌子:

  • 朋友表 ( UserID, FriendID) 和

  • 用户表 ( UserID, FirstName, LastName)。

我正在尝试执行一个 SQL 查询来加入和拉取所有的记录,这些记录的UserIDor FriendIDinside friends 表等于用户的 ID,但从另一个中拉取FirstNameand 。LastNameUserID

例如

朋友桌

UserID = 1 | FriendID = 2
UserID = 3 | FriendID = 1

用户表

UserID = 1 | FirstName = "Bob"  | LastName = "Hope"

UserID = 2 | FirstName = "John" | LastName = "Doe"

UserID = 3 | FirstName = "Bill" | LastName = "Murray"

如果我以 Bob( = 1) 的身份登录,试图通过检查1 是 a还是在 friends 表中来在一个查询UserID中提取我所有的朋友用户数据 ( FirstNameand )。然后加入不是我的 ID 的相反字段的数据。LastNameUserIDFriendIDUserID

有任何想法吗?

4

3 回答 3

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

@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');
于 2013-01-20T09:14:43.740 回答
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 |

SQL 小提琴演示

于 2013-01-20T09:14:48.763 回答
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

在电话上,因此可能需要语法调整。

优化器可能会根据您的真实数据建议不同的连接策略

于 2013-01-20T09:16:08.307 回答