Yesterday I have been testing one single query for over hours and hours, but I never succeeded. These are the three tables:
USERS:
#### id: 1 ##### name: Admin ##### Hometown: The Hague
POSTS:
#### id: 1 ##### userid: 1 ##### title: Test I ##### opinion: agree
#### id: 2 ##### userid: 1 ##### title: Nope.. ##### opinion: disagree
REACTIONS:
#### id: 1 ##### userid: 1 ##### opinion: agree
#### id: 2 ##### userid: 1 ##### opinion: disagree
And this is what I want:
I want the basic information of the user (name, hometown, etc) and I want to count how much compliments (post – opinion: agree), how much complaints (post – opinion: disagree), how much positive reactions (reaction – opinion: agree) and how much negative reactions (reaction – opinion: disagree) this person has posted.
This is the query I use now:
SELECT
u.name, u.hometown,
SUM(IF(r.opinion="disagree",1,0)) AS agrees
SUM(IF(r.opinion="disagree",1,0)) AS disagrees,
SUM(IF(p.opinion="agree",1,0)) AS compliments,
SUM(IF(p.opinion="disagree",1,0)) AS complaints
FROM
users AS u
LEFT JOIN
reactions AS r
ON
r.userid = u.id
LEFT JOIN
posts AS p
ON
p.userid = u.id
WHERE
u.id = 1
The problem is that this does not give me the correct information. It returns values like 8 positive reactions, though there are only two reactions in the DB.
I think it has something to do with GROUP BY p.id, r.id but I tried that and it did not work… Could someone enlighten me?
Thanks in advance!
Depending on your DBMS, you might be able to do this: