Imagine 2 squares. Each of them is a table. It could be 20 squares instead, or any number of them. But 2 is an easy example. If you draw those 2 squares, with one on top of another one, that's a union query. If you draw them side by side, with 1 on the left and 1 on the right, that's a join.
Looking through your PHP code, I see a lot of AND NOT X = Y. I suppose that works, but it's confusing! If you're able to make sense of it, more power to you, but many people would prefer using a not equals operator ( which could be expressed as != or <> depending on your system). Sometimes it's a good idea to do that, so that if you show this to a PHP+MySQL expert ( I'm more of an ASP.NET+SQL Server guy) it will be easier for them to understand, and hence give you good advice.
Why are you saying Sex = "Male" And NOT SEX = "undefined"? ( I'm taking a space to mean undefined.) Each of your columns is set up this way, but if one of your columns matches an exact value, that means by definition it isn't blank.
PS - You should really use a stored procedure with input parameters, instead of nasty, multi lingual dynamic SQL. That approach would have avoided this problem all together.
|