Showing “Subscriber” Posts And User's Own Posts

北慕城南 提交于 2019-12-11 13:16:39

问题


This has stumped me for some time.

My problem: I have 2 different tables.. A table for user posts and a table for subscribers.

The subscribers table looks like this:

SubscriberID -> ProfileID
1 -> 2
1 -> 3
2 -> 3
2 -> 4
3 -> 2

My posts table looks like this:

PostID -> AuthorID -> PostDate -> PostBody
1 -> 2 -> 12/20/12 -> Hello Word
2 -> 3 -> 12/21/12 -> Bye Bye World
3 -> 1 -> 12/22/12 -> Oh Wait
4 -> 4 -> 12/23/12 -> Is anyone still here?

Basically, how it works is that the user with the ID is subscribed to the user with the ID 2 and 3. ID #2 is subscribed to ID #3 and #4. If a user is subscribed to a certain user, they can see only posts from the person they subscribed to. Now, I'm using the following I saw in a similar question:

SELECT POSTS.*
FROM POSTS
JOIN SUBSCRIBERS
ON POSTS.AUTHORID = SUBSCRIBERS.PROFILEID
WHERE SUBSCRIBERS.SUBSCRIBERID = ?
ORDER BY POSTS.POSTID DESC LIMIT 10

This works fine, but it does not show the user's post as well. I've tried modifying it, but it's not working :\

If you're wondering, the "?" represents the user's ID

So if you can, it would be great if someone could tell me how to include the user's own posts alongside with the posts from the people the user subscribes to


回答1:


You can do it modifying your query to :

SELECT POSTS.*
FROM POSTS
LEFT JOIN SUBSCRIBERS
ON POSTS.AUTHORID = SUBSCRIBERS.PROFILEID
WHERE SUBSCRIBERS.SUBSCRIBERID = ? OR POSTS.AUTHORID = ?
GROUP BY POSTS.POSTID ORDER BY POSTS.POSTID DESC LIMIT 10 

It selects the user own posts as well. Hope this would help.

Updated : Added GROUP BY POSTS.POSTID so duplicates are removed as you only look for data in POSTS table.

When you run query like passing values- Eg. for user having id 1 the query looks like :

SELECT POSTS.*
FROM POSTS
LEFT JOIN SUBSCRIBERS
ON POSTS.AUTHORID = SUBSCRIBERS.PROFILEID
WHERE SUBSCRIBERS.SUBSCRIBERID = 1 OR POSTS.AUTHORID = 1 GROUP BY POSTS.POSTID
ORDER BY POSTS.POSTID DESC LIMIT 10

Results are :

PostID  AuthorID    PostDate    PostBody

3       1   2012-12-21  Oh Wait
2       3   2012-12-21  Bye Bye World
1       2   2012-12-20  Hello Word

This is what you get when pass values to the select query properly. The values passed to SUBSCRIBERID and AUTHORID should be same. The LEFT JOIN would fix your problem.



来源:https://stackoverflow.com/questions/8584224/showing-subscriber-posts-and-users-own-posts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!