I have a simple address book type of database. I’ve probably overnormalised, but it’s as much about productivity as it is learning.
I have a table, PEOPLE, with an ID (generated identity), first/last names, title, etc. Also has a foreign key “spouse” on the ID field in its own table. Obviously, nullable.
I have a table, ADDRESSES, with an ID (generated identity), and all the details required for snail mail.
I have a table, PERSONADDRESS, with two foreign keys, PERSON pointing to PEOPLE.ID, and ADDRESS pointing to ADDRESSES.ID.
Theoretically, I’ll have an EMAILS table with the foreign key to PEOPLE and the email. Theoretically, people (geeks like me) can have more than one email. And other relations between similar data in the future. (PHONES, etc.).
So, with that, the problem is this. I want to produce some address labels. (Yes, it’s getting a little late for Christmas cards.) So, to get Libreoffice to do this, I think I need to create a view that LO can read its data from, where every field I want to spit out is already available.
This is somewhat simple enough, except that, at the moment, I have a bit too much duplication. My view is created as such:
CREATE OR REPLACE VIEW ADDRBOOK.LABELS AS
WITH T AS (
SELECT DISTINCT
P1.ID AS AID,
P1.TITLE AS ATITLE, P1.GIVENNAME AS AGIVEN, P1.LASTNAME AS ALAST,
P2.TITLE AS BTITLE, P2.GIVENNAME AS BGIVEN, P2.LASTNAME AS BLAST,
A.STREET, A.MUNICIPALITY, A.STATE, A.COUNTRY, A.POSTALCODE
FROM
ADDRBOOK.ADDRESSES A
JOIN
ADDRBOOK.PERSONADDR PA
ON PA.ADDRESS = A.ID
JOIN
ADDRBOOK.PEOPLE P1
ON PA.PERSON = P1.ID
LEFT OUTER JOIN
ADDRBOOK.PEOPLE P2
ON P1.SPOUSE = P2.ID
ORDER BY P1.ID
)
SELECT DISTINCT
ATITLE, AGIVEN, ALAST,
BTITLE, BGIVEN, BLAST,
STREET, MUNICIPALITY, STATE, COUNTRY, POSTALCODE
FROM T
;
However, this means that if persons A and B are married, I’m going to get one entry where A is showing up under ATITLE, AGIVEN, ALAST, and B is BTITLE, BGIVEN, BLAST, and another entry where they’ve reversed positions. The distinct obviously doesn’t work because they’re simply in different columns. I’m having trouble imagining the changes I would need to make this exclusion.
Note that disconnecting one of the two people from the address, which would be a simple solution for this particular issue, would run counter to the general table data concept: to hold all these relationships for whatever purpose, and then extract what I need when I need it. Granted, it’s 90% labels at this point, but as long as it’s a learning excersise, I’m hoping someone can help me out here.
Add this where clause to your temp table query. Nearly all of these types of AB/BA problems can be solved by similar comparison.