PHP mysql how to link three tables showing results from different tables

I have this chart POST WITH FEEDS

What I want to do is: Likes post - like Facebook

How do you manage to query this?

I have this code

SELECT users.firstname, users.lastname, 
       users.screenname, posts.post_id, posts.user_id,
       posts.post, posts.upload_name, 
       posts.post_type, posts.date_posted
FROM website.users users
INNER JOIN website.posts posts ON (users.user_id = posts.user_id)
ORDER BY posts.pid DESC
//PROBLEM with this one is that it only views the post from all users.

//SO I added
SELECT COUNT(user_id) AS friends, SUM(user_id = ?) AS you, user_id
FROM feeds WHERE post_id = ?
//This one will give you two fields containing how many different users **feeds** the
post

Please help the guys. In fact, it’s just me following the Facebook “LIKE” status that I’m not a fan of such things, so I would be glad to hear all your answers. I really need your help.

+5
source share
2 answers

, feeds ( posts, feeds), GROUP BY post.pid, SELECT .

MySQL GROUP_CONCAT() , ( group_concat_max_len), "" ( SEPARATOR, ).

SELECT users.firstname, users.lastname, 
       users.screenname, posts.post_id, posts.user_id,
       posts.post, posts.upload_name, 
       posts.post_type, posts.date_posted,
       COUNT(feeds.user_id) AS friends,   -- number of "likes"
       SUM(feeds.user_id = ?) AS you,     -- did I like this?
       GROUP_CONCAT(feeds.user_id)        -- who likes it?
FROM website.users users
INNER JOIN website.posts posts ON (users.user_id = posts.user_id)
LEFT  JOIN website.feeds feeds ON (posts.post_id = feeds.post_id)
GROUP BY posts.pid
ORDER BY posts.pid DESC

UPDATE

, "" , , users:

SELECT users.firstname, users.lastname, 
       users.screenname, posts.post_id, posts.user_id,
       posts.post, posts.upload_name, 
       posts.post_type, posts.date_posted,
       COUNT(feeds.user_id) AS friends,                      -- number of "likes"
       SUM(feeds.user_id = ?) AS you,                        -- did I like this?
       GROUP_CONCAT(
         CASE WHEN NOT likes.user_id = ? THEN                -- exclude self
           CONCAT_WS(' ', likes.firstname, likes.lastname)   -- full names
         END
       )
FROM website.users users
INNER JOIN website.posts posts ON (users.user_id = posts.user_id)
LEFT  JOIN website.feeds feeds ON (posts.post_id = feeds.post_id)
LEFT  JOIN website.users likes ON (feeds.user_id = likes.user_id)
GROUP BY posts.pid
ORDER BY posts.pid DESC
+3

, feed:

SELECT u.firstname, u.lastname, 
   u.screenname, p.post_id, p.user_id,
   p.post, p.upload_name, 
   p.post_type, p.date_posted,
   COUNT(f.user_id) AS friends, SUM(f.user_id = ?) AS you
FROM website.users u
INNER JOIN website.posts p ON (u.user_id = p.user_id)
LEFT  JOIN website.feeds f ON (p.post_id = f.post_id)
GROUP BY p.pid
ORDER BY p.pid DESC

...

+2

All Articles