优化MySQL的简单查询

时间:2012-11-11 02:46:51

标签: php mysql sql performance

我有脚本:

SELECT *, (pbct_hits + (COUNT(likes.rvw_usr_like) * 5) - (COUNT(unlikes.rvw_usr_like)) * 5) AS score
FROM tb_publications
LEFT JOIN tb_reviews_users likes ON likes.rvw_usr_fk_publication = pbct_id AND likes.rvw_usr_like IS TRUE
LEFT JOIN tb_reviews_users unlikes ON unlikes.rvw_usr_fk_publication = pbct_id AND unlikes.rvw_usr_like IS FALSE
GROUP BY pbct_id
ORDER BY score DESC;

我不想在同一张桌子上进行两次连接。

我相信可以优化上面的脚本,但我没有。

修改

问题解决了:

-- Final Script:
SELECT pbct.*
FROM tb_publications pbct
LEFT JOIN tb_reviews_users ON rvw_usr_fk_publication = pbct_id
GROUP BY pbct_id
ORDER BY
(
(pbct_hits * 1) +
((SUM(CASE WHEN rvw_usr_like IS TRUE THEN 1 ELSE 0 END)) * 5) -
((SUM(CASE WHEN rvw_usr_like IS FALSE THEN 1 ELSE 0 END)) * 5)
) DESC, pbct_record ASC;

基于@MikeSmithDev的回答。

2 个答案:

答案 0 :(得分:1)

怎么样?
SELECT pbct_id, 
score = 
  (pbct_hits + 
     ((SUM(CASE WHEN rvw_usr_like IS TRUE THEN 1 ELSE 0 END)) * 5) -
     ((SUM(CASE WHEN rvw_usr_like IS FALSE THEN 1 ELSE 0 END)) * 5))
    FROM tb_publications
    LEFT JOIN tb_reviews_users likes ON likes.rvw_usr_fk_publication = pbct_id 
    GROUP BY pbct_id

这应该可行......或者在SQL上使用数学在php端做更简单的事情

答案 1 :(得分:0)

我不会在查询中做那样的数学运算。我愿意:

SELECT *
FROM tb_publications
LEFT JOIN tb_reviews_users review_users ON review_users.rvw_usr_fk_publication = pbct_id
GROUP BY pbct_id

然后我会手动在php中进行数学运算

$score = 0;
if($row['rvw_usr_like'])
   $score += 5;

此外,根据您是否更频繁地插入喜欢或显示得分,您可能需要考虑在出版物表中存储总得分。