I am currently trying to count how many dislikes and likes users have given to an image on my website, underneath you will see the database setup I did for exactly that. Vote_type keeps the like and dislike information where 1 is equal to a like, 0 is equal to a dislike.
this table is called projects
This table is called projects_votes
Now I want to include that when I make a query to drag information from my database for a blog post. This is currently the query I am making to get the necessary information to display a list of blogs on the frontpage. Here I am getting the uploader, project ID for links and so on.
$query = " SELECT * FROM projects LEFT JOIN users ON fk_usr_id = usr_id LEFT JOIN projects_maps ON fk_project_id = project_id ORDER BY RAND() ";
So what I have a hard time understanding is how to count my Likes and Dislikes on a specific blog, so I can display this information on my website.
I solved my problem by changing my query to this statement here.
$query = " SELECT project_id, usr_publicname, project_name, photofile_name, map_version, usr_publicname, map_date, project_id AS project, (SELECT COUNT(*) FROM projects_votes WHERE vote_type = 1) AS likes, (SELECT COUNT(*) FROM projects_votes WHERE vote_type = 0) AS dislikes FROM projects LEFT JOIN projects_votes ON fk_project_id = project_id LEFT JOIN users ON projects.fk_usr_id = usr_id LEFT JOIN projects_maps ON projects_maps.fk_project_id = projects.project_id LEFT JOIN photos ON photos.fk_project_id = projects.project_id GROUP BY project_id ORDER BY RAND() ";
maybe something like this?
SELECT project_id, sum(case when vote_type = 1 then 1 else 0 end) likeCount, sum(case when vote_type = 0 then 1 else 0 end) dislikeCount FROM projects LEFT JOIN users ON fk_usr_id = usr_id LEFT JOIN projects_maps ON fk_project_id = project_id GROUP BY project_id