Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Please, try this query (also on <a href="http://www.sqlfiddle.com/#!2/48b44/3" rel="nofollow">SQL Fiddle</a>): </p> <pre><code>SELECT p.id, p.user_id, m.username, m.privacy, searcher.username "Searcher", p.status_msg FROM posts p JOIN members m ON m.id = p.user_id LEFT JOIN following f ON p.user_id = f.user_id JOIN members searcher ON searcher.username = 'userA' WHERE (m.privacy = 0 OR (m.privacy = 1 AND f.follower_id = searcher.id) OR m.id = searcher.id) AND p.status_msg LIKE '%New%' ORDER BY p.id LIMIT 5; </code></pre> <p>I removed <code>username</code> field from <code>posts</code> table, as it is redundant. Also, I named tables and columns slightly different, so query might need cosmetic changes for your schema.</p> <p>The first line in the <code>WHERE</code> clause is the one that you're looking for, it selects posts in the following order:</p> <ol> <li>First posts from members without privacy;</li> <li>Then posts from members that are followed by the current <code>searcher</code>;</li> <li>Finally, posts of the member himself.</li> </ol> <hr> <p><strong>EDIT:</strong></p> <p>This query is using original identifiers: </p> <pre><code>SELECT p.id, p.`userID`, m.username, m.privacy, searcher.username "Searcher", p.`statusMsg` FROM posts p JOIN `myMembers` m ON m.id = p.`userID` LEFT JOIN following f ON p.`userID` = f.user_id JOIN `myMembers` searcher ON searcher.username = 'userD' WHERE (m.privacy = 0 OR f.follower_id = searcher.id OR m.id = searcher.id) AND p.`statusMsg` LIKE '%New%' ORDER BY p.id LIMIT 5; </code></pre> <hr> <p><strong>EDIT 2:</strong></p> <p>To avoid duplicates in case there're several followers for the user from the <code>posts</code> table, join and filtering conditions should be changed the following way (on <a href="http://www.sqlfiddle.com/#!2/a6262/31" rel="nofollow">SQL Fiddle</a>): </p> <pre><code>SELECT p.id, p.user_id, m.username, m.privacy, searcher.username "Searcher", p.status_msg FROM posts p JOIN members m ON m.id = p.user_id JOIN members searcher ON searcher.username = 'userC' LEFT JOIN following f ON p.user_id = f.user_id AND follower_id = searcher.id WHERE (m.privacy = 0 OR (m.privacy = 1 AND f.id IS NOT NULL) OR m.id = searcher.id) ORDER BY p.id LIMIT 5; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload