1

我需要通过 (LIKES (puntuacion=1) - DISLIKE (puntuacion=0) 的结果来排序此查询的结果。

这是我按喜欢的总和(puntuacion = 1)排序的旧查询。

"SELECT entradas.* , SUM(puntuacion) AS total_likes
            FROM entradas
            LEFT JOIN valoraciones ON valoraciones.entradas_id = entradas.id
            and valoraciones.puntuacion=1
            WHERE fecha>=:fecha1 AND aceptada=1
            GROUP BY entradas.id
            ORDER BY  `total_likes` DESC
            limit 5";

试过这个,但 total_likes / total_dislikes 是时间变量,不能对它们进行操作。

     SELECT entradas.* , SUM(puntuacion=1) AS total_likes, SUM(puntuacion=0) AS total_dislikes, total_likes-total_dislikes AS TOTAL
            FROM entradas
            LEFT JOIN valoraciones ON valoraciones.entradas_id = entradas.id
            WHERE aceptada=1
            GROUP BY entradas.id
            ORDER BY  `total_likes` DESC
            limit 5
4

1 回答 1

1
SELECT entradas.* , (SUM(v1.puntuacion) - SUM(v0.puntuacion)) AS total_likes
FROM entradas
LEFT JOIN valoraciones v1 ON v1.entradas_id = entradas.id and v1.puntuacion=1
LEFT JOIN valoraciones v0 ON v0.entradas_id = entradas.id and v0.puntuacion=0
WHERE fecha >= :fecha1 AND aceptada=1
GROUP BY entradas.id
ORDER BY  `total_likes` DESC
limit 5

[编辑]

对不起,伙计,上面的查询不太好。我认为您正在寻找的正确答案是以下这个:

SELECT entradas.* , SUM(IF(v.puntuacion = 1, 1, -1)) AS total_likes
FROM entradas
LEFT JOIN valoraciones v ON v.entradas_id = entradas.id
WHERE fecha >= :fecha1 AND aceptada=1
GROUP BY entradas.id
ORDER BY  `total_likes` DESC
LIMIT 5
于 2013-04-22T10:40:54.603 回答