我试图使主页有点像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
答案 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 BY
或DISTINCT 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'