I need to pass the OD.ID from the parent query's current record to the subquery. I have no idea how to do this, or even if it's possible to do.
The value of OD.ID (line 4 below) will be a unique number for each row in the parent query, and I need to limit the subquery to only records in the OD table that have that ID (attempted on line 10 below). The goal is for the query on line 10 to return a value representing the number of distinct days a person with the given ID has placed an order. The OD database contains a record for each individual item purchased for every order and has columns for purchase day and ID of the purchaser, among other columns. Is it possible to do this?
public static function getAthleteReportByDates($start_date, $end_date){
return Database::runQuery(
"SELECT
OD.ID,
IF(ISNULL(A.FuelID)=1, 'No Fuel ID', A.FuelID) AS FuelID,
IF(ISNULL(CONCAT(FirstName, ' ', LastName))=1, 'N/A', CONCAT(FirstName, ' ', LastName)) As Name,
IF(ISNULL(A.Gender)=1, 'N/A', A.Gender) AS 'Gender',
IF(ISNULL(S.Name)=1, 'N/A', S.Name) As Sport,
SUM(F.Price) As Total,
SUM(F.Price) / (Select Count(Distinct OD.Day, OD.ID) From OrderDetail OD Where (OD.Day Between :start_date And :end_date AND OD.ID = [Pass down value of current parent record's OD.ID here])) AS Average
From OrderDetail OD
LEFT JOIN Food F
ON OD.FoodID = F.ID
LEFT JOIN Athlete A
ON A.ID = OD.ID
LEFT JOIN PlaysFor PR
ON PR.ID = OD.ID
LEFT JOIN Sports S
ON PR.SPORT_ID = S.ID
Where Day Between :start_date And :end_date
Group By OD.ID, Sport",
array(
'start_date' => $start_date,
'end_date'=> $end_date
));
}
This is called a 'correlated subquery'. You just need to use a different alias in the subquery so you can refer to OD.ID and it knows you mean the outer one:
(Select Count(Distinct OD2.Day) From OrderDetail OD2 Where OD2.Day Between :start_date And :end_date AND OD2.ID = OD.ID)