简体   繁体   English

PHP - 比较来自两个MySQL表的Connections / Feed

[英]PHP - Compare Connections/Feed from two MySQL Tables

I am working on a small social networking project that will allow users to connect with each other, similar to the "friends" idea of Facebook. 我正在开发一个小型社交网络项目,允许用户相互联系,类似于Facebook的“朋友”想法。 The site has it's own unique features that set it apart from others, so please hold the comments about the social networking market being saturated. 该网站拥有自己独特的功能,使其与众不同,所以请关注社交网络市场饱和的评论。

Each time a user connects with a friend, it is added to the 'Connections' table in the MySQL DB. 每次用户与朋友连接时,都会将其添加到MySQL DB中的“Connections”表中。 Each time a user sends a gift, invite or anything else, it is added to the 'Feed' table. 每次用户发送礼物,邀请或其他任何内容时,都会将其添加到“Feed”表中。

I need to be able to display only the activity of friends from the 'Feed' table, based on the connections in the 'Connections' table. 我需要能够根据“连接”表中的连接,仅显示“Feed”表中的朋友的活动。

My first thought was to collect all of the connection for the currently logged in user from the 'Connections' table and place the IDs in an array. 我的第一个想法是从“Connections”表中收集当前登录用户的所有连接,并将ID放在一个数组中。 Then loop through that array, checking each ID against the 'Feed' table for activity. 然后循环遍历该数组,根据“Feed”表检查每个ID的活动。 This, however, just doesn't seem like a reasonable way to do this. 然而,这似乎不是一种合理的方法。 It will also group all of the activity of each user together, instead of in the order it happened. 它还将每个用户的所有活动组合在一起,而不是按顺序组合。

Any ideas? 有任何想法吗?

Something along the lines of a straight forward join: 沿着直接连接的方向:

SELECT feed.*
FROM connections
JOIN feed
  ON connections.friend_id = feed.user_id
WHERE connections.user_id = <insert id of user>

You can use IN clause in mysql, try this.. 你可以在mysql中使用IN子句,试试这个..

select * 
from feeds f 
where user_id IN (
    select friends_id 
    from connections 
    where user_id = $user_id
)

OR 要么

select * 
from feeds f join connections c 
on c.friends_id = f.user_id 
where c.user_id = $user_id

Joins are faster than sub-queries, also don't forget to add indexes on related columns(friends_id, user_id). 联接比子查询更快,也不要忘记在相关列(friends_id,user_id)上添加索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM