1

For the past days i've been trying to create a SQL query to show posts between friends. However, I can't figure out what i'm doing wrong. For me it looks like the posts repeats itself and behave differently than my intension.

This query is "supposed" to show posts from me and users that are friends with me.

SELECT *
FROM bhost_entries
WHERE
  author_u_id='$user_info[u_id]'
  OR author_u_id IN (SELECT follower_u_id
                     FROM bhost_userfollow
                     WHERE following_u_id='$user_info[u_id]')
ORDER BY e_id DESC

Tables:

bhost_entries:     e_id, author_u_id, title
bhost_userfollow:  uf_id, following_u_id, follower_u_id

Am I completely off track? Appreciate any thoughts.

Output (when following 2 users)

Heihei
Aker Brygge-spesial
Vi har oppdatert retningslinjene
Hei, dette er en kladd!
To do list
Testinnlegg
Push Notifications
Californication
Hank Moody
Hei bloggen
Heihei
Aker Brygge-spesial
Vi har oppdatert retningslinjene
Hei, dette er en kladd!
To do list
Testinnlegg
Push Notifications
Californication
Hank Moody
Hei bloggen
8
  • Can you show us the output that you get, and that looks wrong to you?
    – Borniet
    Apr 10, 2013 at 10:33
  • What do you mean? How should i do that? @Borniet Apr 10, 2013 at 10:34
  • Run the query, then copy and paste the output into your answer (assuming the results aren't enormously long).
    – user359040
    Apr 10, 2013 at 10:37
  • What about SELECT * FROM bhost_entries LEFT JOIN bhost_entries ON (bhost_userfollow.following_u_id = bhost_entries.author_u_id) WHERE (bhost_entries.author_u_id = '$userinfo[uid]')?
    – Voitcus
    Apr 10, 2013 at 10:43
  • Something like that? As of now i'm following 2 users, and this is the output. @MarkBannister Apr 10, 2013 at 10:43

2 Answers 2

0

If I could test it, I would have done this :

SELECT e_id, author_u_id, title
FROM bhost_entries, bhost_userfollow
WHERE
  author_u_id='$user_info[u_id]'
  OR (follower_u_id='$user_info[u_id]' AND following_u_id=author_u_id)
ORDER BY e_id DESC
GROUP BY e_id
2
  • Every post gets repeated. Any clue? Apr 10, 2013 at 12:24
  • That means it works? I've added a group by to avoid repetitions.
    – Julien
    Apr 10, 2013 at 12:36
0

You could try something like this:

SELECT DISTINCT (e.e_id) AS entry_id,
       e.title AS entry_title, 
       e.author_u_id AS author_id
FROM bhost_entries AS e
JOIN bhost_userfollow AS f
ON (f.following_u_id = e.author_u_id) 
WHERE (e.author_u_id = '$user_info[u_id]' OR f.follower_u_id = '$user_info[u_id]')

if i understand it correctly it does the trick. check out here: SQL Fiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.