The database I am working with currently does have two tables, one holding the attribute “contact_person”. This attribute is compared to several attributes (not tuples!) in another table which are named “contact1” to “contact4” to determine what other attributes to display from the second table (i.e. “email1” to “email4”). So the first table only holds the contact person, the second the actual address data for several contact persons (again, all of them in a row or a single tuple). Do not tell me that this aint proper database design – I have to work with what I was given -.-
To get the proper contact data I chose to perform a select for each comparison and UNION them. This works fine and executes well enough for the application that performs the query. It looks, very simplified, something like this:
SELECT contact1, email1, phone1 FROM T1,T2 WHERE contact_person = contact1
UNION ALL
SELECT contact2, email2, phone2 FROM T1,T2 WHERE contact_person = contact2
UNION ALL
SELECT contact3, email3, phone3 FROM T1,T2 WHERE contact_person = contact3
UNION ALL
SELECT contact4, email4, phone4 FROM T1,T2 WHERE contact_person = contact4
Now, due to malformed and non-error-checked INSERT queries, it is possible that “contact_person” is NULL or an empty string or that any of the “contactN” attributes is NULL. So I need another SELECT query that displays all records that are in the database but are not in the record-set yet.
With the given example that could be achieved using something similar to this:
UNION
SELECT contact_person, 'N/A', 'N/A' FROM T1,T2
In the real life query I (need to) do a lot of formatting of “contact_person” and the “contactN”s, so simply doing a UNION (without the ALL, so equal records get excluded) wont work (contactN is actually a multi field value and the formatting is not consistent, so the records returned by the last query might differ from the records above, even for the same entry in the database). Also, the query is so enormous already that it is no option to use the opposite of the first query to exclude its records, like so:
UNION ALL
SELECT contact_person, 'N/A', 'N/A' FROM T1,T2
WHERE contact_person <> contact1
AND contact_person <> contact2
AND contact_person <> contact3
AND contact_person <> contact4
So is there another way to display all records that have not been selected with the very first query posted above? Maybe by somehow running a subquery (ofc there does exists a UID for the returned records – I just dont know how to work with it in this context)? Could the very first query have been written in a simpler way?
You might also consider a more normalized/relational design?