Jump to content


Photo

JOIN GROUP help...


  • Please log in to reply
3 replies to this topic

#1 ViperSBT

ViperSBT
  • Members
  • PipPipPip
  • Advanced Member
  • 49 posts

Posted 23 June 2006 - 02:17 PM

OK, so it is the most complex query that I have put together to date...

The query looks like this:
SELECT d.dnumber, d.cname, MIN( s.time ) AS singles, SUM( p.points ) AS points
FROM dads d
LEFT JOIN singles s ON s.dad = d.dnumber
LEFT JOIN points p ON p.dad = d.dnumber
WHERE d.cat =45 && d.payment != 'pending'
GROUP BY d.dnumber
ORDER BY cname

The result shows all the rows I am expecting, and everything is in order except for the 'points' result. It appears that the sum of all the points entries in the points table for a particular dad are being multiplied by the number of entries that dad is showing up in the singles table. Does that make sense?

So a dad that has 100 points and is in the singles table once = 100, which would be correct.
A dad that has 100 points and in the singles table 3 times = 300, which is incorrect and should only be the 100.

#2 Wildbug

Wildbug
  • Members
  • PipPipPip
  • Advanced Member
  • 1,149 posts

Posted 23 June 2006 - 03:08 PM


Well, if a dad is in the table three times, and the point=100 for each entry, then SUM is just doing what you asked it to, and adding up the points (which would be, and is, 300). If there are duplicate entries in your table, and the "points" value is always equal for them, then you don't need the SUM if you just want to return the points. Use "p.points" instead of "SUM(p.points)". Will that work for you?
Twice a day my clock works PERFECTLY!  I can't figure out what's wrong with it.

#3 ViperSBT

ViperSBT
  • Members
  • PipPipPip
  • Advanced Member
  • 49 posts

Posted 24 June 2006 - 12:16 AM

A dad is a single entry in the 'dads' table. A dad MAY have multiple entries in both the 'singles' and 'points' tables. So what I am wanting to do is find out what the smallest number is for a dad in the 'singles' table as well as the total number of points the dad has earned by summing all of his results from the 'points' table...

#4 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 25 June 2006 - 01:54 PM

Beacuse of the doubling-up effect of multiple joins you will need a subquery or, if Mysql version < 4.1, a temporary table.
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users