I have a database setup as follows (simplified):
+----------+---------+----------+
| path | val1 | val2 |
+----------+---------+----------+
| a/ | two | cow |
+----------+---------+----------+
| a/b/ | one | cat |
+----------+---------+----------+
| a/b/c | NULL | bat |
+----------+---------+----------+
path is the primary key (in actual use, more like Smith/John/Mark/Jr).
PHP provides a path $mypath = "a/b/c";
Is there a way to build a result set of non null values, choosing from all rows whose path is part of $mypath.
That is, to search for the key that matches most exactly, find all non-null values in it, and if there are any nulls, to get them from the second-“best” key.
Eg. Mysql should check a/b/c and return a val2 = “bat”, but see that val1 is set to NULL.
It should therefore check a/b/ and set val1 = “one”;
The final result should be array('val1' => "one", 'val2' => "bat").
A friend told me there is a way with “LOCATE”, but I couldn’t work it out.
Is this doable?
And can someone who knows MySQL help me rewrite the title of this question to be more descriptive?
Thanks.
In conclusion:
It is probably impossible to do as requested using only SQL.
However, SQL can get an multidimensional array from the matching keys, and PHP can whittle it down to one array.
If anyone can improve this to only use SQL (as in the question posted), it would be much appreciated.
SQL:
PHP:
You can see this in practice at http://codepad.org/UnyEZJ6a
Notes:
Hope this can help someone else!