有两个问题,想知道它们是否可以合并



所以我有两个查询,我试图在循环中运行一个(没有成功(,但我认为我可能可以将其中两个组合起来。

profile_posts
ID
post_title
post_bodyems>user_ID>
>post_date<1br>

profile_post_likes
ID
点赞
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语句,但没有成功。感谢您的帮助。提前谢谢。

您可以使用join:来表达您的查询

SELECT ppl.id, ppl.user_Like_id, ppl.post_id
FROM profile_posts_likes ppl
INNER JOIN
(
SELECT *
FROM profile_posts
WHERE user_id = :id
ORDER BY post_date DESC
LIMIT $limit
) pp
ON pp.id = ppl.post_id;

在第二个查询中选择COUNT毫无意义,因为您没有使用GROUP BY

相关内容

  • 没有找到相关文章

最新更新