Mysql Self Join to find a parent child relationship in the same table

混江龙づ霸主 提交于 2019-12-09 21:29:05

问题


Im trying to calculate the amount of money won by all the offspring of a male race horse (Sire) over a time period. Listed by the Sire with the most amount of money won. I run the query and get the result Im after with one problem, I cant display the sires name, only their ID.

SELECT  `horses`.`SireID` AS  `SireID` , `horses`.`HorseName` AS  `Sire Name`, 
                  COUNT(  `runs`.`HorsesID` ) AS  `Runs` , 
                  COUNT( 
                           CASE WHEN  `runs`.`Finish` =1
                                THEN 1 
                                ELSE NULL 
                                END ) AS  `Wins` , 
                  CONCAT( FORMAT( (
                                COUNT( 
                                       CASE WHEN  `runs`.`Finish` =1
                                            THEN 1 
                                            ELSE NULL 
                                            END ) / COUNT
                                    (  `runs`.`TrainersID` ) ) *100, 0 ) ,  '%'
                  ) AS  `Percent` , 
           FORMAT( SUM(  `runs`.`StakeWon` ) , 0 ) AS  `Stakes` 
FROM runs
INNER JOIN horses ON runs.HorsesID = horses.HorsesID
INNER JOIN races ON runs.RacesID = races.RacesID
WHERE  `races`.`RaceDate` >= STR_TO_DATE(  '2012,07,01',  '%Y,%m,%d' ) 
AND  `races`.`RaceDate` < STR_TO_DATE(  '2012,07,01',  '%Y,%m,%d' ) + INTERVAL 1 
MONTH 
AND `horses`.`SireID`  <> `horses`.`HorsesID`
GROUP BY  `horses`.`SireID`, `horses`.`HorseName`
ORDER BY SUM(  `runs`.`StakeWon` ) DESC

Take a record in the horse table for example, a horse has a horsesID and they also have a sireID (their father). The sireID has an equivalent horsesID in another record in the same table as it is also a horse

Basically I need to map the horseName to the sireID.

I thought a self join would work.

 `AND `horses`.`SireID`  <> `horses`.`HorsesID`` 

but it doesn't return the correct Sire name corresponding to the SireID.


回答1:


You can do a JOIN on the table itself. Here's a simpler example:

SELECT Horses.HorseID, Horses.HorseName, Horses.SireID, b.HorseName as SireName
FROM Horses
LEFT JOIN Horses b ON (Horses.SireID = b.HorseID)

You can probably figure out how to add the conditions from here.




回答2:


join horses sires on sires.HorsesID = horses.SireID



来源:https://stackoverflow.com/questions/12694986/mysql-self-join-to-find-a-parent-child-relationship-in-the-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!