2011-11-22 81 views
1

我有如下表:移調查詢PostgreSQL中

tb_item 
id_item | item_name | price 
---------------------------- 
1  | item1  | 2000 
2  | item2  | 3000 
3  | item3  | 4000 

tb_value 
id_value | id_item | value_type | value 
---------------------------------------- 
1  | 1  | bedroom | 2 
2  | 1  | bathroom | 1 
3  | 2  | bedroom | 3 
4  | 2  | bathroom | 1 
5  | 3  | bedroom | 4 
6  | 3  | bathroom | 2 

我想獲得類似這樣的輸出:

item_name | price | bedroom | bathroom 
--------------------------------------- 
item1  | 2000 | 2  | 1 
item2  | 3000 | 3  | 1 
item3  | 4000 | 4  | 2 

我使用PostgreSQL的;什麼查詢可以用來獲得這個輸出? 我也使用PHP;有沒有一個PHP函數可以做到這一點?

+0

查找 '支點查詢'。 –

+0

這是功課嗎? –

+0

@JonathanLeffler,我可以直接使用這些功能嗎?或者之前需要安裝? – Praditha

回答

2

您也可以與一對夫婦完成這個LEFT JOIN聲明

SELECT i.item_name 
    , i.price 
    , bed.value AS bedroom 
    , bath.value AS bathroom 
FROM tb_item AS i 
LEFT JOIN tb_value AS bed ON i.id_item = bed.id_item 
    AND bed.value_type = 'bedroom' 
LEFT JOIN tb_value AS bath ON i.id_item = bath.id_item 
    AND bath.value_type = 'bathroom' 
+0

+ 1用於將'JOIN'條件與WHERE過濾條件分開。 –

+0

@ A.H。是的,對不起。我已經更新了它,謝謝你的提醒。 –

+0

非常感謝,我想投你的答案,但我還是不能這樣做,:D – Praditha

0
select item_name, price, bedroom.value as bedroom, bathroom.value as bathroom 
from tb_item, tb_value as bedroom, tb_value as bathroom 
where bedroom.id_item=tb_item.id_item and bedroom.value_type='bedroom' 
and bathroom.id_item=tb_item.id_item and bathroom.value_type='bathroom'