I have a problem here.
Right now i have three tables (Pet, Address, Contact):
USER TABLE COLUMNS:
PET_ID_PK
PETNAME
ADDRESS_ID_FK
CONTACT_ID_FK
GENDER
OWNER_ID
BOUGHT_DATE
ADDRESS TABLE COLUMNS:
ADDRESS_ID_PK
ADDRESS_STRING
CONTACT TABLE COLUMNS:
CONTACT_ID_PK
CONTACT_NUMBER
I want to join these tables into one table with the columns:
PET_ID_PK
PETNAME
ADDRESS_STRING
CONTACT_NUMBER
GENDER
And I hope to get the pets that belong to a specific OWNER_ID and display the rows in the order of GENDER (FEMALE first, then MALE). In this case, i can use ORDER BY CASE.
But in each user table entry, either ADDRESS_ID_FK or CONTACT_ID_FK will be a NULL value.
So with reference to a solution provided in Unioning Two Tables With Different Number Of Columns that counteracts columns with NULL value, I came up with the query:
SELECT DISTINCT ON (pets.pet_id_pk) * FROM
((SELECT pet_id_pk, petname, address_string, NULL AS contact_id_fk, gender
FROM user JOIN address ON address.address_id_pk=address_id_fk)
UNION
(SELECT pet_id_pk, petname, NULL AS address_string, contact_id_fk, gender
FROM user JOIN address ON contact.contact_id_pk=contact_id_fk) AS pets
WHERE OWNER_ID=$1 ORDER BY (CASE WHEN gender=female ELSE 2 END), bought_date DESC
However this query is not working accordingly.
Hope someone could help me out with this. Thank you.
Please try below:
You could use LEFT JOIN. LEFT JOIN will display the table even thou there is no match result.
For the ORDER BY, i don’t really see the need to use CASE as by using only ORDER BY, it will display FEMALE follows by MALE. Do you have any specific reason for using ORDER BY CASE ?