在PHP和MySQL中显示我的帖子以及关注者帖子

时间:2016-02-26 23:57:57

标签: php mysql inner-join

我试图使主页有点像Facebook,我这么做就可以显示我关注的人的帖子,但我无法看到自己的帖子,因为我无法做到跟着自己。这是我编写的SQL代码行(它包含PHP变量):

SELECT * 
FROM user_posts 
INNER JOIN user_following ON user_posts.username = user_following.username 
WHERE user_following.follower = '$me->username' 
ORDER BY id DESC 
LIMIT 0, 15
  1. user_posts表包含所有帖子。
  2. user_following表包含所有关注数据,其中username是被关注的用户,而follower是跟随username的用户
  3. $me->username是登录用户的用户名。
  4. user_posts表结构: enter image description here

    user_following表结构: enter image description here

    先谢谢!

2 个答案:

答案 0 :(得分:3)

有几种不同的方法来验证这个查询:

<强>子查询

SELECT * 
FROM user_posts 
WHERE user_posts.username = 'bob'
OR user_posts.username IN(
  SELECT username 
  FROM user_following
  WHERE user_posts.username = user_following.username
)
LIMIT 0, 15

http://sqlfiddle.com/#!9/6bf2c6/9

使用用户表

需要GROUP BYDISTINCT user_posts.id,这些都不是最佳的。

SELECT
   user_posts.* 
FROM users
LEFT JOIN user_following ON users.username = user_following.username
INNER JOIN user_posts ON (
  users.username = user_posts.username
  OR user_following.follower = user_posts.username
)
WHERE users.username = 'bob'
GROUP BY user_posts.id
LIMIT 0, 15

http://sqlfiddle.com/#!9/d91be/1

重要!确保并在表格中为这些列编制索引。否则,随着表格变大(特别是user_following),性能将受到影响。

答案 1 :(得分:0)

试试这段代码:

select * 
from user_posts up 
join user_following uf on up.username = uf.username
where uf.follower = '$me->username'
or up.username = '$me->username'