我有這些下表:sql查詢與條件上加入連接表
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條與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。
在phone_numbers表上做第二次左連接,但是這次使用'fax'的phone_type。 – Bobby 2014-09-24 07:57:07
讓試試下面這個鏈接可以幫助你, http://stackoverflow.com/questions/12169016/simple-pivot-sample – RickyRam 2014-09-24 08:05:54