bltopaz said:
I have data sets that have married couples, the couples have the same last
name, I want to create a query that shows the last name plus the name of the
husband and the name of the wife on one row.
This can be tricky because your constraints need to ensure couples are
one known male and one known female, one person can only be married to
one other person, etc
CREATE TABLE People
(key_col INTEGER NOT NULL,
last_name VARCHAR(35) NOT NULL,
first_name VARCHAR(35) NOT NULL,
sex_code INTEGER DEFAULT 0 NOT NULL,
CHECK (sex_code in (0, 1, 2)),
PRIMARY KEY (key_col, sex_code));
CREATE TABLE Marriages
(male_key_col INTEGER NOT NULL UNIQUE,
male_sex_code INTEGER NOT NULL,
CHECK (male_sex_code = 1),
CONSTRAINT fk__marriages__people__male
FOREIGN KEY (male_key_col, male_sex_code)
REFERENCES People (key_col, sex_code)
ON DELETE CASCADE
ON UPDATE CASCADE,
female_key_col INTEGER NOT NULL UNIQUE,
female_sex_code INTEGER NOT NULL,
CHECK (female_sex_code = 2),
CONSTRAINT fk__marriages__people__female
FOREIGN KEY (female_key_col, female_sex_code)
REFERENCES People (key_col, sex_code)
ON DELETE CASCADE
ON UPDATE CASCADE,
PRIMARY KEY (male_key_col, female_key_col));
SELECT P2.first_name AS wife_name, P1.first_name AS husband_name,
P2.last_name AS married_name
FROM (People AS P1 INNER JOIN Marriages
ON Marriages.male_key_col = P1.key_col)
INNER JOIN People AS P2
ON Marriages.female_key_col = P2.key_col
AND P1.last_name = P2.last_name