我以为我已经解决了这个问题,但我刚刚意识到指定一个与朋友表中任何人都不是朋友的用户会导致该用户无法看到任何帖子,这不是我想要的行为。< / p>
被阻止的用户的类别为4.我知道我可以从帖子中返回所有评论,然后手动检查该用户的类别是否为4,但这是不必要的计算,可以通过单一查询(我认为)。
SELECT DISTINCT
ent.Entity_Id,
ent.Profile_Pic_Url,
ent.First_Name,
ent.Last_Name,
ent.Last_CheckIn_Place,
comments.Content,
friends.Category
FROM
checkin_comments AS comments
JOIN entity AS ent
ON comments.Entity_Id = ent.Entity_Id
JOIN friends
ON comments.Entity_Id = friends.Entity_Id1
OR comments.Entity_Id = friends.Entity_Id2
WHERE
comments.Chk_Id = 1726
AND friends.Category != 4
GROUP BY comments.Comment_Id
这将返回所有结果,因为无法指定登录用户。然后我想提供一个子查询:
SELECT DISTINCT
ent.Entity_Id,
ent.Profile_Pic_Url,
ent.First_Name,
ent.Last_Name,
ent.Last_CheckIn_Place,
comments.Content,
friends.Category
FROM
checkin_comments AS comments
JOIN entity AS ent
ON comments.Entity_Id = ent.Entity_Id
JOIN friends
ON comments.Entity_Id = friends.Entity_Id1
OR comments.Entity_Id = friends.Entity_Id2
WHERE
comments.Chk_Id = 1726
AND friends.Category = (
SELECT Category FROM friends
WHERE
friends.Entity_Id1 = 1527
AND friends.Entity_Id2 = comments.Entity_Id
OR friends.Entity_Id1 = comments.Entity_Id
AND friends.Entity_Id2 = 1527
)
-- filter out blocked users as they have a category of 4
AND friends.Category != 4
GROUP BY comments.Comment_Id
这里的想法是获取每个用户的类别,然后根据它来过滤结果集,这种工作方式,在某种意义上它返回所有朋友的用户列表,但它不会占用由非朋友(朋友表中不存在)发表评论的用例。
如何修复此查询以便返回所有用户,并且只显示类别为4的用户?
如果您需要更多信息,请询问。
答案 0 :(得分:1)
您正在寻找外部联接。您的第一个查询的变体应该可以解决这个问题:
SELECT DISTINCT
ent.Entity_Id,
ent.Profile_Pic_Url,
ent.First_Name,
ent.Last_Name,
ent.Last_CheckIn_Place,
comments.Content,
friends.Category
FROM
checkin_comments AS comments
JOIN entity AS ent
ON comments.Entity_Id = ent.Entity_Id
LEFT JOIN friends
ON comments.Entity_Id = friends.Entity_Id1
OR comments.Entity_Id = friends.Entity_Id2
WHERE
comments.Chk_Id = 1726
AND IFNULL(friends.Category, 0) != 4
GROUP BY comments.Comment_Id
如果评论作者未通过friends
表与请求者关联,则评论将包含在联接结果中,所有列都来自friends
{{1} }。 NULL
子句中的IFNULL()
通过将WHERE
类别转换为值NULL
来处理该问题(尽管实际上除了0
之外的任何值都可以)。