1

我有一个名为 Friends 的表,其结构如下:

id, from_id, to_id, confirmed, ....

此表包含所有用户的所有好友列表。from_id 和 to_id 包含用户的 id,其中 from_id 是实际发送好友请求的用户。

现在,我需要选择一个特定用户的所有好友列表。

最好使用以下查询或联合查询:

"select (from_id + to_id)- $user_id as friend_id, ... from friends where from_id=$user_id or to_id=$user_id"
4

3 回答 3

1

我会使用一个union(确保你有索引from_idto_id):

select from_id from friends where to_id = $user_id
union
select to_id from friends where from_id = $user_id

在我看来,这种方式更清楚。

于 2012-04-06T18:56:05.423 回答
1

假设您在 id 上有键,则联合肯定会更好,然后执行算术运算。

于 2012-04-06T18:56:40.653 回答
1

虽然我喜欢你的数学风扇解决方案,但我认为它没有考虑溢出问题。例如:如果将两个非常大的数字相加会发生什么?

除此之外,您的解决方案依赖于数字 user_id。使用联合可能需要更多时间(您应该测试以确保),但适用于任何数据类型。

于 2012-04-06T19:19:30.923 回答