【问题标题】:How can i order two tables?我如何订购两张桌子?
【发布时间】:2020-01-31 09:16:27
【问题描述】:

我有两个 桌子users ('ID' 'username' '...')connectivities('ID' 'following_ID' '...')

每次一个用户关注另一个用户时,都会在connectivities 中创建一个条目。关注者在查询后按用户 ID 降序排列。现在我不想按 ID 而是按 connectivities 中的条目对关注者进行排序。所以总是最先显示最后一个新的关注者。

    public function getFollowers($offset = false,$limit = null){
    if (empty($this->user_id) || !is_numeric($this->user_id)) {
        return false;
    }

    else if (!empty($limit) && !is_numeric($limit)) {
        return false;
    }

    $user_id = $this->user_id;
    $t_users = T_USERS;
    $t_conn  = T_CONNECTIV;

    self::$db->join("{$t_conn} c","c.follower_id = u.user_id AND c.type = 1","INNER");
    self::$db->where("c.following_id",$user_id);
    self::$db->orderBy("u.user_id","DESC");

    if (!empty($offset) && is_numeric($offset)) {
        self::$db->where("u.user_id",$offset,'<');
    }

    $users = self::$db->get("{$t_users} u",$limit);
    $data  = array();

    foreach ($users as $key => $user_data) {
        $user_data = $this->userData($user_data);
        $user_data->is_following = false;

        if (IS_LOGGED) {
            $this->user_id = self::$me->user_id;
            $user_data->is_following = $this->isFollowing($user_data->user_id);
        }

        $data[]    = $user_data;
    }

    return $data;
}

如果我将 self :: $ db-&gt; orderBy ("u.user_id", "DESC"); 更改为 self :: $ db-&gt; orderBy ("c.id", "DESC"); 也可以,但总是显示相同的前 20 个条目。 然后总是重复这些。我认为问题是偏移量。

有人知道吗?

【问题讨论】:

  • 不确定你想在这里做什么。也许您可以提供一个示例数据集以及您希望它如何排序?
  • 我想按 ID DESC 表“连接”对查询进行排序。到目前为止,当我将行更改为 orderBy ("c.id", "DESC") 但仅适用于大约 20 个条目
  • 如果我理解正确的话,您想同时按用户 ID 和关注者 ID 对其进行排序,不是吗?先按用户排序,再按每个用户的关注者排序?

标签: php sql codeigniter sql-order-by


【解决方案1】:

调用$db-&gt;orderBy 两次,按u.userid desc, c.id desc 对行进行排序

self::$db->join("{$t_conn} c","c.follower_id = u.user_id AND c.type = 1","INNER");
self::$db->where("c.following_id",$user_id);
self::$db->orderBy("u.user_id desc","c.id desc");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多