简体   繁体   English

如何执行MySQL查询以获取不同订阅中按ID排序的所有行?

[英]How to perform MySQL query to get all the rows from different subscriptions sorted by id?

A user has subscriptions. 用户已订阅。 They are stored in PHP array. 它们存储在PHP数组中。 I am trying to get all of the posts that belong to subscriptions ordered by id to display in the news feed. 我正在尝试获取所有属于ID订阅的帖子,以显示在新闻Feed中。 I was trying to get all of them looping throw the array, and after that sorting them by ID. 我试图让所有这些对象循环抛出该数组,然后按ID对它们进行排序。 I am wondering if there is an easier way for that, as I decided to use the 'LIMIT' in order to get only the specific amount of posts. 我想知道是否有更简单的方法,因为我决定使用“ LIMIT”以仅获取特定数量的帖子。

The problem is that now, I get all of the posts, and I need only 10 (for example). 问题是,现在,我收到了所有帖子,而我只需要10个帖子。 I am using PDO, MySQL, PHP. 我正在使用PDO,MySQL,PHP。 Here is the code I have now: 这是我现在拥有的代码:

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'];
});

Now, if I will limit to 10, I will get 10 posts for each of subscriptions, but I need 10 in summary (the latest ones (ordered by 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'];
});

If you have an array of subscriptions i can suggest to use IN clausole. 如果您有一系列订阅,我建议您使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM