Selecting 1 Instance of a Client's family in MySQL
What I need to return from the query is a list of Heads of Households who have visited in the past year and all of their relatives. Everyone is in the Client table which is joined to the other tables when queried.
The problem is that the query returns a "set" of Family members for each unique DateVisited. I'm hoping to get a set of results that looks like this (I omitted some columns for clarity):
Head of househo开发者_如何学编程ld Relative/child
---------------------------- ---------------------
John Smith - Katie Smith
John Smith Joe Smith
Tim Jones Mike Jones
Tim Jones Sally Jones
Kevin Barnett Corey Barnett
Kevin Barnett Cara Barnett
Kevin Barnett Austin Barnett
SELECT f.HeadOfHouseholdID,
CONCAT( c.lastname, ', ', c.firstname ) AS 'HName',
v.Datevisited, f.RelationshipID, c2.ClientID,
CONCAT( c2.lastname, ', ', c2.firstname ) AS 'Relative Name'
FROM client c
INNER JOIN clientfamily f ON c.ClientID = f.HeadOfHouseholdID
JOIN visits v ON c.clientid = v.clientID
JOIN client c2 ON c2.clientid = f.relativeID
WHERE v.datevisited BETWEEN CURDATE( ) - INTERVAL 1 YEAR AND CURDATE( )
![Query Results][1]
A coworker figured it out:
SELECT f.HeadOfHouseholdID 'HOHID',
CONCAT( c.Lastname, ', ', c.FirstName ) AS 'Head of Household',
c.PhoneNumber AS 'HOH Phone',
f.RelativeID,
CONCAT( C2.Lastname, ', ', C2.FirstName ) AS 'Relative',
Relationship.Description AS 'Relation',
C2.PhoneNumber AS 'Relative Phone', C2.DOB,
(
(
DATE_FORMAT( NOW( ) , '%Y' ) - DATE_FORMAT( C2.DOB, '%Y' )
) -
( DATE_FORMAT( NOW( ) , '00-%m-%d' ) < DATE_FORMAT( C2.DOB, '00-%m-%d' ) )
) AS Age
FROM client c
INNER JOIN clientfamily f ON c.clientid = f.headofhouseholdid
JOIN (
SELECT ClientID, MAX( DateVisited ) AS 'DateVisited'
FROM Visits
GROUP BY ClientID
) v ON c.clientid = v.clientid
JOIN client c2 ON c2.clientid = f.relativeid
JOIN Relationship ON f.RelationshipID = Relationship.RelationshipID
WHERE v.datevisited
BETWEEN CURDATE( ) - INTERVAL 1 YEAR
AND CURDATE( )
精彩评论