I need to order the result of this query by the result of (LIKES (puntuacion=1) - DISLIKE (puntuacion=0).
This is the old query where I order by the sum of likes (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";
Tried this, but total_likes / total_dislikes are temporal variables and can't operation with them.
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
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
[EDIT]
Sorry mate, the query abover is not quite alright. I think the right answer for what you are looking for is this one below:
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