[英]How to perform MySQL query to get all the rows from different subscriptions sorted by id?
用戶已訂閱。 它們存儲在PHP數組中。 我正在嘗試獲取所有屬於ID訂閱的帖子,以顯示在新聞Feed中。 我試圖讓所有這些對象循環拋出該數組,然后按ID對它們進行排序。 我想知道是否有更簡單的方法,因為我決定使用“ LIMIT”以僅獲取特定數量的帖子。
問題是,現在,我收到了所有帖子,而我只需要10個帖子。 我正在使用PDO,MySQL,PHP。 這是我現在擁有的代碼:
foreach(subscriptions_arr as $sub) {
$select = $db->prepare("select * from posts where owner_id = :owner_id");
$select->bindParam(':owner_id', $sub);
$select->execute();
$posts = $select->fetchAll(PDO::FETCH_ASSOC);
// pushes all of the posts into one multi-array with only 2 levels
// (instead of 3 as before)
// to be able to sort it by id, and not by subscriptions
foreach ($posts as $post) {
$new_array[] = $post;
}
}
// sorts by id
usort($new_arr, function($a, $b) {
return $b['id'] - $a['id'];
});
現在,如果我限制為10個,則每個訂閱將獲得10個帖子,但摘要中需要10個帖子(最新的帖子(按ID排序))。
$select = $db->prepare("select * from posts where owner_id = :owner_id order by id");
這樣,記錄將以升序排序,請閱讀有關ORDER BY子句的信息。
foreach(subscriptions_arr as $sub) {
$select = $db->prepare("select * from posts order by ID DESC group by owner_id LIMIT 10");
$select->execute();
$posts = $select->fetchAll(PDO::FETCH_ASSOC);
// pushes all of the posts into one multi-array with only 2 levels
// (instead of 3 as before)
// to be able to sort it by id, and not by subscriptions
foreach ($posts as $post) {
$new_array[] = $post;
}
}
// sorts by id
usort($new_arr, function($a, $b) {
return $b['id'] - $a['id'];
});
如果您有一系列訂閱,我建議您使用IN Clausole。
$select = $db->prepare("select * from posts where owner_id IN(" .
implode(',',subscriptions_arr).") ORDER BY owner_id";
$result = $select->execute();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.