Issue
Question: Can someone help me fix the following piece of code to meet the following info:
When using this query, it sees that my username is in the database multiple times on diff columns, and so it is duplicating my posts when finding them in the query. I WANT it to show posts at diff timestamps by the same person, but not display from the same person if timestamp is the same.
Might be a better way to code the query, if so, I wouldn't mind seeing those options. Would doing a UNION query be the best way to do this?
$query = "SELECT p.* ".
"FROM posts p ".
"INNER JOIN friendships f ON p.username = f.user2 OR p.username = f.user1 ".
"WHERE f.user1 = '$sessionusername' OR f.user2 = '$sessionusername' ORDER BY id DESC";
SOLUTION:
I am answering my own question here, just to give someone a workable solution from what I did to fix the issue. I tried grouping by ID and then turning around and ordering by ID; however, it threw an error -- so instead I am ordering by timestamp, and grouping by ID. Below is my code. Worked for me -- and hopefully this ends up helping someone else!
$query = "SELECT p.*, MAX(timestamp) AS latest ".
"FROM posts p ".
"INNER JOIN friendships f ON p.username = f.user2 OR p.username = f.user1 ".
"WHERE f.user1 = '$sessionusername' OR f.user2 = '$sessionusername' GROUP BY id ORDER BY latest DESC";
Solution
Use GROUP BY to tell mysql what entity/fields you want to be unique:
SELECT p.*
FROM posts p
INNER JOIN friendships f ON (p.username = f.user2 OR p.username = f.user1)
WHERE f.user1 = '$sessionusername' OR f.user2 = '$sessionusername'
GROUP BY posts.id
ORDER BY id DESC
Answered By - Puggan Se Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.