我目前正在制作一个供稿页面,其中包含在一个页面上显示所有帖子,相片和评论的内容。我有三张不同的桌子。一个包含帖子,一个包含喜欢,一个包含评论。
所有帖子都可以正确显示和显示。然而,问题出现在2个或更多人喜欢的帖子时,它也会在帖子中重复帖子2次或更多次。以下是我的代码:
scroll
我的Feed数据库中只有2个帖子,而在FeedLikes中,第一篇帖子中有两个匹配。但是,第一篇文章会显示两次。
如果我$findShouts = $pdo->prepare('
SELECT f.id
, f.username
, f.name
, f.text
, f.timestamp
, l.likesUsername
, c.commentsUsername
, c.commentsName
, c.commentsText
, c.commentsTimestamp
FROM feed f
LEFT
JOIN feedLikes l
ON l.likesFeedID = f.id
LEFT
JOIN feedComments c
ON c.commentsFeedID = f.id
WHERE f.name IN (SELECT scoutingUsername
FROM scout
WHERE scoutedUsername =?
OR scoutingUsername =?)
ORDER
BY f.timestamp DESC
');
//execute query and variables
$findShouts->execute([$username, $username]);
if ($findShouts->rowCount() > 0)
{
//get the shouts for each scout
while($row = $findShouts->fetch(PDO::FETCH_ASSOC)){
$shoutID[] = $row['id'];
$shoutUsername[] = $row["username"];
$shoutName[] = $row["name"];
$shoutText[] = $row["text"];
$shoutTimestamp[] = $row["timestamp"];
$likesUsername[] = $row['likesUsername'];
$commentsUsername[] = $row["commentsUsername"];
$commentsName[] = $row["commentsName"];
$commentsText[] = $row["commentsText"];
$commentsTimestamp[] = $row["commentsTimestamp"];
}
$shoutCount = count($shoutUsername);
for($indexShout=0; $indexShout < $shoutCount; $indexShout++) {
//show post data
}
}
我只期望2个结果(每个帖子一个),但是它显示3个,因为第一个帖子的2个喜欢创建2个相同的帖子。
感谢您的帮助。
答案 0 :(得分:0)
您可以使用PHP在稍后阶段选择和解析所有数据。 不是实现任务的最佳方式,但值得一试:
SELECT f.id
, f.username
, f.name
, f.text
, f.timestamp
, Group_concat(l.likesUsername order by l.likesUsername separator ',') as likesUsername
, Group_concat(c.commentsUsername order by c.commentsUsername separator ',') as commentsUsername
, Group_concat(c.commentsName order by c.commentsUsername separator ',') as commentsName
, Group_concat(c.commentsText order by c.commentsUsername separator ',') as commentsText
, Group_oncat(c.commentsTimestamp order by c.commentsUsername separator ',') as commentsTimestamp
FROM feed f
LEFT
JOIN feedLikes l
ON l.likesFeedID = f.id
LEFT
JOIN feedComments c
ON c.commentsFeedID = f.id
WHERE f.name IN (SELECT scoutingUsername
FROM scout
WHERE scoutedUsername =?
OR scoutingUsername =?)
Group by f.id // added group by
ORDER
BY f.timestamp DESC