0

我有脚本:

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 的回答。

4

2 回答 2

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

那应该可以工作......或者在 php 端使用数学在 SQL 中做一些更简单的事情

于 2012-11-11T03:44:01.613 回答
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;

此外,根据您是更频繁地插入喜欢还是显示分数,您可能需要考虑在发布表中存储总分数。

于 2012-11-11T03:02:01.613 回答