我这里有问题。
现在我有三个表(宠物,地址,联系人):
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
我想将这些表连接到一个包含列的表中:
PET_ID_PK
PETNAME
ADDRESS_STRING
CONTACT_NUMBER
GENDER
并且我希望得到属于特定OWNER_ID的宠物,并按照GENDER的顺序显示行(先FEMALE,然后是MALE)。在这种情况下,我可以使用 ORDER BY CASE。
但在每个用户表条目中,ADDRESS_ID_FK 或 CONTACT_ID_FK 将是 NULL 值。因此,参考联合两个具有不同列数的表中提供的解决方案来抵消具有 NULL 值的列,我想出了查询:
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
但是,此查询没有相应地工作。
希望有人可以帮助我解决这个问题。谢谢你。