I have this member table where memberships are either single or family, and if family they can be family head or dependent. When outputting a view of the membership, it currently sorts alpha ascending, but I'd like to find a way to put all of the dependents of a family head below the head.
The relevant columns are:
isFam ( tinyint(1) )
isFamHead ( tinyint(1) )
memKey ( int(11) )
Is there some way, in a mysql query, to sort the table alphabetically for single members and family heads, but put the dependents of the family head directly beneath the family head?
(This sort of works right now if all family members have the same last name, but in many cases I find they don't. And different families can have the same last name as well, so …)
From the comments:
memKey
identifies a membership. For a single membership, there will be only one row with thatmemKey
; for a family membership, all members of a given family will have the samememKey
.- For a single membership,
isFam
is 0; for all members of family memberships,isFam
= 1. - The "family head" of each family membership has
isFamHead
= 1; there should only be one row whereisFamHead
= 1 permemKey
. (Ignore value ofisFamHead
for single members)
Best Answer
So - making the following assumptions:
memKey
is the same for a family head and all subsidiary memberships for the family;isFamHead
acts as a Boolean, where "1" means the row represents a family head, and "0" means it doesn't.memKey
whereisFamHead
= 1From the comments: Members with "single" memberships (1 person, no family) will have
isFam
= 0. Members who are part of a family membership will haveisFam
= 1; only the primary member from the family will haveisFamHead
= 1, it will be 0 for the rest.Something like this should work. Column and table names are made up, of course, since none were provided except for the three relevant columns.
Our subquery adds the first and last name of the
isFamHead
row for the current row'smemKey
to the current row's data.Then, we sort by: - the family head's last and first names -
memKey
(just in case there are two family heads with the same name - this pulls each actual family group together) -isFamHead
in descending order - this makes the family head the first row of each family group - finally, the members' last and first names.If we have the following families:
memKey
= 10000)memKey
= 10001)This should give us the following output:
NOTE: code is untested.