Question

So I'm making a intranet/site which will display latest 'posts' to groups the user is subscribed to How can I select (in mysql) only the posts for the groups the user is subscribed to?

My current code is:

SELECT posts.groupid, groups.groupid, mygroups.groupid
FROM posts, groups, mygroups
WHERE posts.groupid = mygroups.groupid

So pretty much, I only want the mysql to return all the posts that the user is subscribed to. So if user1 is subscriber to group1 and NOT group2 then mysql will only return group1 posts.

Table structure:

---Posts:---
postid
groupid
postmessage
postowner
postdate

---groups:---
groupid
owner
groupname
groupyear

---mygroups:---
userid
groupid

---users:---
id
username
password
email
realname
lastip
role
avatarurl
pushid
Was it helpful?

Solution

You have to do it with an inner join:

SELECT postid, postmessage 
FROM posts 
INNER JOIN mygroups 
ON posts.groupid = mygroups.groupid 
WHERE mygroups.userid = *theUsersUserId*

OTHER TIPS

This should work, given a single user id:

SELECT groupid, postid
FROM mygroups
JOIN posts USING (groupid)
WHERE userid = <user id goes here>

To me this looks pretty straightforward and achieved by two inner joins. Try

SELECT a.userid, b.postid
FROM users a, posts b, mygroups c
WHERE b.userid=a.id
AND   c.groupid=b.groupid

Your basic query will be something like:

SELECT * FROM posts INNER JOIN mygroups ON posts.groupid=mygroups.groupid;

Then you can filter by the user in the WHERE clause.

SELECT * FROM posts INNER JOIN mygroups ON posts.groupid=mygroups.groupid WHERE userid='user1';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top