我正在尝试创建一个视图来输出用户朋友的所有帖子。问题是我得到帖子的重复输出。正如您在视图中看到的那样,我得到2行同一帖子。有没有办法将列user1和user2分组为这样的帖子
post
user1 user2
user1 user2
而不是像目前正在做的那样
post user1 user2
post user1 user2
下面是我的表结构
+----------------------------------------------+
| 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'));
答案 0 :(得分:1)
您可以通过在user1和user2上应用group_concat
来获得预期的输出(不同的帖子)
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