I have an unusual SQL table (not mine) that has the following fields (among others): last_name, primary_name, secondary_name
denoting married couples. It is assumed that the surname is common (not very modern, I know), and if it is not a pair, then either primary_name
or secondary_name
can be NULL. (There are also some duplicates in the table.)
What I want to do is get a list of all the names ("first last") in the database, in alphabetical order in the usual order. Now I am doing two passes through the database using PHP and PDO:
$qstr = "SELECT DISTINCT primary_name, last_name FROM members WHERE primary_name IS NOT null ORDER BY last_name, primary_name"; $sth = $dbh->prepare($qstr); $sth->execute(); // output the results $qstr = "SELECT DISTINCT secondary_name, last_name FROM members WHERE secondary_name IS NOT null ORDER BY last_name, secondary_name"; $sth = $dbh->prepare($qstr); $sth->execute(); // output the new results
But the end result is not in alphabetical order, because the second pass begins again.
How can I get all the names at once, in alphabetical order completely? Is there a way to do this in SQL, or do I need to build two arrays and regroup them in PHP afterwards?
EDIT The database looks something like this:
last_name primary_name secondary_name ---------------------------------------- Abrams Joe Susan Miller Sam Abby
The desired result will be something like this:
["Joe Abrams","Susan Abrams","Abby Miller","Sam Miller"]
Instead, if the first pass gets all husbands and the second gets all wives, I get something like this:
["Joe Abrams","Sam Miller","Susan Abrams","Abby Miller"]