【发布时间】:2025-12-17 11:15:01
【问题描述】:
所以我有 2 个查询,我试图在循环内运行一个(不成功),但我认为我可能可以将其中 2 个结合起来。
表格 profile_posts
ID
post_title
post_body
user_id
post_date
表profile_posts_likes
ID
likes
user_like_id
post_id
$baseURL = 'Data.php'; //Grab page for pagination
$id = $_GET['id']; //Grab id from link
$limit = 10; //Limit returns to 10
//Select statement that grabs results from profile_posts table
$postQuery = "SELECT * FROM profile_posts WHERE user_id = :id ORDER BY post_date DESC LIMIT $limit"; //First Query
// Count of all records
$rowCount = countRecords($conn, $id);
// Initialize pagination class
$paginationConfig = array(
'postID' => $id,
'baseURL' => $baseURL,
'totalRows' => $rowCount,
'perPage' => $limit,
'contentDiv' => 'postContent',
'link_func' => 'searchFilterProfile'
);
$pagination = new Pagination($paginationConfig);
$profilePost = $conn->prepare($postQuery);
$profilePost->bindParam(":id", $id);
$profilePost->execute();
if($profilePost->rowCount() > 0){
foreach($postDisplay as $row){
$likeQuery = "SELECT id, COUNT(likes) as likeCount, user_Like_id, post_id FROM profile_posts_likes WHERE post_id = :postID"; //Second Query
$likeQuery = $conn->prepare($likeQuery);
$likeQuery->bindParam(":postID", $row['id']); //Grab id from first query
$likeQuery->execute();
$postlikeQuery = $likeQuery->fetchAll();
if($likeQuery->rowCount() > 0){
//Display like buttons, when user clicks "Like" button, send data through Ajax
//and update page with "Liked"
}
}
}
这样做是在用户个人资料页面上显示帖子,然后当用户查看他们的页面时,他们可以“喜欢”帖子或“不喜欢它”...使用 Ajax 更新页面
现在有一种方法可以将这两个查询组合在一起,而不是在循环内运行一个。我试图在那里扔一个 WHERE EXISTS 来组合 Select 语句,但没有运气。 感谢任何帮助。提前致谢。
【问题讨论】:
-
请分享样本数据和样本所需的结果。
-
好的,这就是我想知道的。那么在循环内运行一个查询是否是理想的。我敢肯定这会减慢速度
-
@PHPFromTheBack 您也可以在 profile_posts 表中拥有类似 numOfLikes 的列。只要 profile_posts_likes 表中有插入/删除,您就可以有一个触发器来更新 numOfLikes。参考mysqltutorial.org/mysql-triggers.aspx
-
@Indra Kumar S 这可行,但我希望能够向用户显示他们是否喜欢该帖子。以便他们以后可以“不喜欢”它
-
当你的 profile_posts_likes 表变大时,你的查询会变得很慢。