Reputation: 1415
I am trying to create a view to output all posts by a users friends. The problem is that I get duplicated output of the posts. As you can see below in the view i get 2 rows with the same post. Is there a way to group the columns user1 and user2 with a posts like this
post
user1 user2
user1 user2
and not like its currently are doing
post user1 user2
post user1 user2
Underneath is my table structure
+----------------------------------------------+
| posts |
+----+------+--------+--------+------+---------+
| id | post | postBy | postTo | date | deleted |
+----+------+--------+--------+------+---------+
| 1 | text | 1 | 0 | date | 0 |
+----+------+--------+--------+------+---------+
+---------------------------+
| friends |
+----+-------+-------+------+
| id | user1 | user2 | date |
+----+-------+-------+------+
| 1 | 1 | 2 | date |
| 2 | 1 | 3 | date |
+----+-------+-------+------+
CREATE VIEW posts_by_friend AS SELECT posts.id, posts.post, posts.postBy, posts.postTo, posts.date, posts.deleted, friends.user1, friends.user2 FROM posts
INNER JOIN friends ON (posts.postBy = friends.user1 OR posts.postBy = friends.user2) GROUP BY posts.id, friends.user1, friends.user2
+--------------------------------------------------------------+
| posts_by_friend |
+----+------+--------+--------+------+---------+-------+-------+
| id | post | postBy | postTo | date | deleted | user1 | user2 |
+----+------+--------+--------+------+---------+-------|-------|
| 1 | text | 1 | 0 | date | 0 | 1 | 2 |
| 1 | text | 1 | 0 | date | 0 | 1 | 3 |
+----+------+--------+--------+------+---------+-------+-------+
$userId = 1;
SELECT * FROM `posts_by_friend` WHERE `deleted`=0 AND (`user1`='$userId' or `user2`='$userId'));
Upvotes: 1
Views: 22
Reputation: 64476
You could get the expected output (distinct posts) by applying group_concat
on user1 and user2
CREATE VIEW posts_by_friend AS
SELECT p.id, p.post, p.postBy, p.postTo, p.date, p.deleted, group_concat(f.user1) user1, group_concat(f.user2) user2
FROM posts p
INNER JOIN friends f ON (p.postBy = f.user1 OR p.postBy = f.user2)
GROUP BY p.id, p.post, p.postBy, p.postTo, p.date, p.deleted
Upvotes: 1