Let’s say i have 2 tables Customer and Books.
Table Books can have multiple rows that pertain to a row in Customer.
Ex:
customer John Doe has an id of 1000.
Table Books has 2 rows with a member_id column with 1000 (John Doe).
These 2 rows are identical EXCEPT one of the fields (book title) is empty. The other row has a value for a title.
Question:
How can i query this so that I retrieve the row with the valid title value, BUT, if both title values are empty, then it just returns a single row?
I certainly hope that made sense.
You should be able to use a distinct operator:
If that does not work correctly you could use an inner select:
Also, if this is a frequently used query I would avoid a UNION because they are known to have performance problems.
In response to the edit:
This should return all books associated with a customer (but only one time for each title and if no books are found then it will return an empty string.) If this does not answer the question please include some additional information about the tables and an example of the result you would like and I will update.
OK, now I think I know what you are looking for:
Here is a possible query based on your original question using the tables provided. However, it will not work if the customer has two distinct e-mail addresses set; in that case, you could add a TOP(1) to ensure only one result but you won’t know if it is the “right result.”
Here is another query based on the data you provided and the example output.
I’m not sure how representative your sample data is but why would you be storing the member name in more than one table? That is a guaranteed headache in the future.