背景资料 - 我总共有4张桌子。
我想要实现的目标是:该页面会列出您自己,朋友和您加入的群组的所有帖子。
(以前的查询) - 帖子&小组帖子在同一个表格中,并由“'类型”标识。字段
SELECT
DISTINCT p.id,
p.type,
p.user1,
p.user2,
p.content,
p.timestamp,
p.comments
FROM posts p, friends f, group_memberships g
WHERE (p.user1 = f.user2 AND f.user1 = 'MY ID') OR
p.user1 = 'MY ID' OR
(p.user1 = g.group_id AND g.user = 'MY ID')
ORDER BY p.timestamp, DESC LIMIT 10
以前,我在同一个表中有帖子和group_posts。但现在,我认为它们应该在两个不同的表格中。
(新查询) - 帖子和论坛帖子位于不同的表格中
SELECT
DISTINCT p.id,
p.type,
p.user1,
p.user2,
p.content,
p.timestamp,
p.comments,
gp.id,
gp.type,
gp.user1,
gp.user2,
gp.content,
gp.timestamp,
gp.comments
FROM posts p, group_posts gp, friends f, group_memberships g
WHERE (p.user1 = f.user2 AND f.user1 = 'MY ID') OR
p.user1 = 'MY ID' OR
(p.user1 = g.group_id AND g.user = 'MY ID')
ORDER BY p.timestamp, gp.timestamp DESC LIMIT 10
我得到的结果是我的group_posts中填充了相同帖子的整行。
另外,我在这两个帖子中的ids& group_posts不是按顺序排列的,即帖子可能有100个帖子,但group_posts可能只有30个。
有什么问题?
答案 0 :(得分:0)
试试这个:
SELECT
p.id,
p.type,
p.user1,
p.user2,
p.content,
p.timestamp,
p.comments,
gp.id,
gp.type,
gp.user1,
gp.user2,
gp.content,
gp.timestamp,
gp.comments
FROM posts p, group_posts gp, friends f, group_memberships g
WHERE (p.user1 = f.user2 AND f.user1 = 'MY ID') OR
p.user1 = 'MY ID' OR
(p.user1 = g.group_id AND g.user = 'MY ID')
GROUP BY p.id
ORDER BY p.timestamp, gp.timestamp DESC LIMIT 10;
请注意,将每个帖子DISTINCT
切换为GROUP BY
进行分组。