我有一个代码,用于计算使用不同表格的用户的分数 我在Codeigniter和sql中通过php写了这个,但是这个问题太慢了
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();
}
现在的问题是这段代码太重而且很慢 我如何只用一个查询编写这段代码
感谢
答案 0 :(得分:0)
您可以使用JOIN
计算单个查询中的所有内容,例如:
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;