Author

Topic: MySQL Help Requested... (Read 1179 times)

legendary
Activity: 1400
Merit: 1005
May 13, 2011, 01:57:28 AM
#6
davout, yeah I ended up going the subquery route on suggestion from a friend.

I thought the CASE method might be more efficient (which it might), but I couldn't get it to work right.  It kept clumping up the data into a single person's username.  I'll revisit the issue later on if speed of the query becomes a problem.
legendary
Activity: 1372
Merit: 1007
1davout
May 13, 2011, 01:49:51 AM
#5
Subqueries baby

Code:
SELECT 
  users.name,
  (SELECT COUNT(*) FROM feedback f1 WHERE [it's positive] AND users.name = f1.username) AS positive,
  (SELECT COUNT(*) FROM feedback f2 WHERE [it's negative] AND users.name = f2.username) AS negative
FROM
  users
sr. member
Activity: 406
Merit: 251
May 13, 2011, 01:39:24 AM
#4
Post schema and sample data.
legendary
Activity: 1400
Merit: 1005
May 13, 2011, 01:30:47 AM
#3
Thanks for the suggestion, I'll give it a shot!
administrator
Activity: 5166
Merit: 12850
May 13, 2011, 01:27:45 AM
#2
With PostgreSQL you could do this:
Code:
SELECT users.name, count(CASE WHEN (feedback.type='positive') THEN 1 ELSE NULL END) AS positive, count(CASE WHEN (feedback.type='negative') THEN 1 ELSE NULL END) AS negative FROM users JOIN feedback ON (feedback.name=users.name) GROUP BY users.name;
I don't know if that would work on MySQL.
legendary
Activity: 1400
Merit: 1005
May 12, 2011, 04:14:50 PM
#1
I can't really figure out the best way to do this...

On my website, bitcoinfeedback, I have a few MySQL tables.  One of them is feedback, and one of them is users.

I'd like to easily be able to pull the percentage of positive vs negative vs neutral feedback a user has while generating a list of users, all with one query.

The only way I can think of to do this is to have three more fields in the users table that just keep an updated count of feedback any time someone leaves feedback on a person's profile.  It would run a query to count the three different types of feedback on a given users account, then update those three fields with the count numbers.  When pulling the users into a list, I could easily make whatever calculations I wanted to do with those three count numbers.

Is there a better way to do this?  Currently, feedback "type" is stored within a single varchar field within each feedback.  So the varchar field will either say "positive", "negative", or "neutral".  I can change that to numbers (1, 0, and -1), and say, only do a sum of it divided by the count, but I'd lose visibility of how many of each the person had.

Thoughts?  Other ways of accomplishing the same thing?
Jump to: