SQL命令由一个操作的结果

时间:2013-04-22 10:31:42

标签: mysql sql operation

我需要通过(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

1 个答案:

答案 0 :(得分: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

[编辑]

对不起伙伴,查询abover不太正常。我认为你正在寻找的正确答案如下:

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