sql - sub-queries calculate score

感情迁移 提交于 2019-12-13 02:50:53

问题


I have a code that calculate an score for users using different table I wrote this via php in Codeigniter and sql but this have a big problem that is too slow

 public function getTopUsers($request) {
        // return $request;

        $query = $this->db->query("
            SELECT * FROM users
            WHERE user_is_block = 0
            AND user_is_paid = 1
            ORDER BY id ASC"
        )->result_array();

        foreach($query as $key=>$value) {
            unset($query[$key]['user_token']);
            unset($query[$key]['user_confirmation_token']);
            unset($query[$key]['user_password']);
            $query[$key]['user_score'] = ( ($this->countInvitationByUserID($query[$key]['id']) * 1000) + ($this->getUserLikedCount($query[$key]['id'])) );
        }

        usort($query, function($a, $b) {
            if($b['user_score'] == $a['user_score'])
                return $a['id'] - $b['id'];
            else
                return $b['user_score'] - $a['user_score'];
        });


        return $query;
    }


    public function countcouponByUserID($id) {
        $query = $this->db->query("
            SELECT * FROM payment, coupon, users
            WHERE payment.payment_coupon_id = coupon.id
            AND coupon.coupon_token = users.user_coupon_token
            AND users.id = ?
            AND payment.payment_status = 1", array($id)
        );
        return $query->num_rows();
    }

    public function getUsertabCount($id) {
        $query = $this->db->query("
            SELECT * FROM `users`, post, `tab`
            WHERE users.id = post.post_user_id
            AND tab.tab_post_id = post.post_id
            AND users.id = ?
            AND post.post_is_active = 1", array($id)
        );
        return $query->num_rows();
    }

Now the problem is that this code is too heavy and slow how I can wrote this code in just one query

thanks


回答1:


You can use JOIN to calculate everything in a single query, e .g.:

SELECT u.id, (COUNT(p.*) * 100  - COUNT(l.*)) AS score
FROM users u LEFT JOIN coupon c ON u.user_coupon_token = c.coupon_token 
LEFT JOIN payment p ON p.payment_coupon_id = c.id
LEFT JOIN post po ON u.id = po.post_user_id
LEFT JOIN like l ON l.like_post_id = po.post_id
WHERE u.user_is_block = 0 
AND u.user_is_paid = 1
AND (p.payment_status IS NULL OR p.payment_status = 1)
AND (po.post_is_active IS NULL OR po.post_is_active = 1)
GROUP BY u.id;


来源:https://stackoverflow.com/questions/44735985/sql-sub-queries-calculate-score

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!