Tables
User
id | name | is_active | |
---|---|---|---|
1 | john | john@albert.com | FALSE |
2 | mike | mike@ss.com | TRUE |
3 | monica | monica@dunno.com | TRUE |
4 | joey | joey@as.com | FALSE |
5 | ross | ross@boss.com | FALSE |
Subscriptions
id | house_id | plan name | status |
---|---|---|---|
1 | 1 | A banana a month | inactive |
2 | 2 | An apple a month | active |
3 | 3 | A pear a month | active |
House
id | name |
---|---|
1 | John's House |
2 | Mike's House |
3 | Monica's House |
4 | Joey's House |
5 | Ross's House |
House_Contact (legacy table)
id | house_id | is_primary |
---|---|---|
1 | 1 | TRUE |
2 | 2 | FALSE |
2 | 3 | TRUE |
House_User (new table)
id | house_id | is_owner | user_id |
---|---|---|---|
1 | 2 | FALSE | 2 |
2 | 4 | FALSE | 4 |
3 | 5 | FALSE | 5 |
Expected Results
The resulting table should include the following:
- Does the user have a subscription regardless of status? If so, include, if not, disregard.
- Get
email
&is_active
from User table (if they have subscription) - Get
is_primary
ORis_owner
(if they have a subscription) - Results should be distinct (no duplicate users)
house_id | is_owner | is_active | |
---|---|---|---|
1 | john@albert.com | TRUE | FALSE |
2 | mike@ss.com | FALSE | TRUE |
3 | monica@dunno.com | TRUE | TRUE |
What I tried
SELECT
u.email AS "email",
u.is_active AS "is_active",
h.id AS "house_id",
is_owner
FROM
house c
INNER JOIN (
SELECT
house_id,
user_id
FROM
house_user) hu ON h.id = hu.house_id
INNER JOIN (
SELECT
id,
email,
is_active
FROM
USER) u ON hu.user_id = u.id
INNER JOIN (
SELECT
id,
email,
is_primary
FROM
house_contact) hc ON u.email = ch.email
INNER JOIN (
SELECT
house_id,
is_primary is_owner
FROM
house_contact
UNION
SELECT
house_id,
is_owner is_owner
FROM
house_user) t ON u.id = t.house_id)
ORDER BY
u.email
Results are half than if I remove the INNER JOIN
with UNION
statement. No idea how to proceed.
I'm particularly confused with unifying the column and the possible duplication.