0

I have 2 tables:

one is users with "userid" column, the other one is opinion with "yes" and "no" columns. The "yes" and "no" columns both contain comma separated values.

What I wanted is to count the number of times a "userid" appears in the "yes" column as well as the number of times it appears in the "no" column.

What I have right now is this

SELECT userid, COUNT(yes), COUNT(no)
FROM users LEFT JOIN opinion ON (FIND_IN_SET( userid, yes) > 0)
GROUP BY userid

The above works as it counts the # of times each user appears in the "yes" column but incorrectly on the "no" column. echoing "no" results to the same result as echoing "yes"

Sample data on "users"

1
2
3

Sample data on "yes"

1,2
1,3
2,3
1

Sample data on "no"

1,2
1,2
1,3

desired result is with data above:

users     yes    no
1         3      3
2         2      2
3         2      1

Thanks in advance for any help

3
  • i'm confused. how do you on if it is a yes or a no? Commented Sep 29, 2013 at 13:21
  • what is also your desired result? Commented Sep 29, 2013 at 13:21
  • @491243 edited the question adding the desired result Commented Sep 29, 2013 at 13:32

1 Answer 1

1

Your query needs only a little tweak. Add also a condition that joins userID with column NO on the other table. During counting of values, you also need to use FIND_IN_SET() inside the aggregate function MAX().

SELECT  a.userID,
        SUM(FIND_IN_SET(a.userID, b.yes) > 0) TotalYes,
        SUM(FIND_IN_SET(a.userID, b.no) > 0) TotalNo
FROM    users a
        LEFT JOIN opinion b
            ON FIND_IN_SET(a.userID, b.yes) > 0 OR
                FIND_IN_SET(a.userID, b.no) > 0 
GROUP   BY a.userID
ORDER   BY a.userID
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. that works! now what if i have another column in the opinion table called points and I want to find the sum for each user. Only users in the yes column gets points
it's a column for the opinion tables as well. every row has a corresponding point. Let's say, each of them is 2 points although they may vary. And only the users in the yes column gets to earn the point/s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.