I have 4 tables and Wallpapers, Downloads, Favorites, Votes that are defined as well. Of wallpapers I just need the id.
Table Downloads
+----+---------+---------+
| id | wall_id | user_id |
+----+---------+---------+
| 1 | 1 | 1 |
| 2 | 35 | NULL |
| 3 | 35 | NULL |
+----+---------+---------+
Favorites Tables
+----+---------+---------+
| id | user_id | wall_id |
+----+---------+---------+
| 1 | 12 | 10 |
| 2 | 12 | 2 |
+----+---------+---------+
Votes Table
+----+---------+---------+---------+
| id | user_id | wall_id | type |
+----+---------+---------+---------+
| 1 | 12 | 1 | dislike |
| 2 | 12 | 39 | like |
| 3 | 1 | 2 | like |
| 4 | 2 | 2 | like |
| 5 | 3 | 2 | like |
| 6 | 5 | 2 | dislike |
| 7 | 12 | 10 | like |
| 8 | 12 | 2 | like |
+----+---------+---------+---------+
Basically what I need is a query that gives me back the amount of Downloads, Favorites, Likes and Dislikes of a wallpaper. Try nesting with several LEFT OUTER JOIN like this:
SELECT w.id,COUNT(d.id) AS Downloads,
COUNT(f.id) AS Favorites,
SUM(IF(v.type = 'like',1,0)) AS Likes,
SUM(IF(v.type = 'dislike',1,0)) AS Dislikes
FROM wallpapers AS w
LEFT OUTER JOIN downloads AS d ON w.id = d.wall_id
LEFT OUTER JOIN favorites AS f ON w.id = f.wall_id
LEFT OUTER JOIN votes AS v ON w.id = v.wall_id
WHERE w.id = 2
GROUP BY w.id;
That returns the result of the form that I need but with the wrong calculations that is to say, values are duplicated and other strange things happen.
Results Table
+----+-----------+-----------+-------+----------+
| id | Downloads | Favorites | Likes | Dislikes |
+----+-----------+-----------+-------+----------+
| 2 | 10 | 10 | 8 | 2 |
+----+-----------+-----------+-------+----------+
I understand that it is because the LEFT OUTER JOIN can not be nested like this because the 3 tables must have records that correspond to the id of the first table.
Any Solution?