我有以下表格:
suppliers
id | name
-----------
1 | sample
addresses
id | address | owner_type | owner_id
-------------------------------------
1 | adres | Supplier | 1
phone_numbers
id | number | owner_type | owner_id | phone_type
------------------------------------------------
1 | 12345 | Supplier | 1 | phone
2 | 67890 | Supplier | 1 | fax
对于我来说,地址表似乎不是问题,我使用此查询,我测试了它并且它工作正常。
Select suppliers.*, addresses.address AS address FROM suppliers LEFT JOIN addresses ON (addresses.owner_id = suppliers.id AND addresses.owner_type = 'Supplier')
现在问题出现在phone_number
表中,有2条不同条件的记录,如你所见:
id | number | owner_type | owner_id | phone_type
------------------------------------------------
1 | 12345 | Supplier | 1 | phone
2 | 67890 | Supplier | 1 | fax
有phone_type
字段 - > phone
和fax
,我希望在结果中显示这两个内容,如下所示:
id | name | address | phone | fax
---------------------------------
1 | sample | adres | 12345 | 67890
我尝试这个查询:
LEFT JOIN phone_numbers ON (phone_numbers.owner_id = suppliers.id AND phone_numbers.owner_type = 'Supplier' AND phone_type = 'phone')
不幸的是,查询仅针对1个条件(phone
),我如何获得传真值?
我使用PostgreSQL。
答案 0 :(得分:0)
您可以使用不同的别名连接phone_numbers表两次。一个用于电话,另一个用于传真。如下P1用于手机,P2用于传真。
Select suppliers.*, addresses.address AS address ,P1.number as 'Phone', P2.number as 'Fax'
FROM suppliers
LEFT JOIN addresses ON (addresses.owner_id = suppliers.id AND addresses.owner_type = 'Supplier')
LEFT JOIN phone_numbers P1 ON (P1.owner_id = suppliers.id AND P1.owner_type = 'Supplier' AND P1.phone_type = 'phone')
LEFT JOIN phone_numbers P2 ON (P2.owner_id = suppliers.id AND P2.owner_type = 'Supplier' AND P2.phone_type = 'fax')