2012-11-12 147 views
2

加入我有3個tabels以下定義Select查詢語句中Postresql

people 
------ 
- wid 
- name 

types 
----- 
- guid 
- type 

mapping 
------- 
- guid 
- wid 

百姓餐桌擁有人

的類型表中的每個類型信息列表排在人桌上。如果一個人屬於多個類型,那麼類型表中會出現兩行。

映射表提供了人員和類型表之間的映射。

現在要找出誰是「政客」類型的人,我可以使用以下查詢。

select name from people inner join 
(mapping inner join types on mapping.guid = types.guid) 
on people.wpid = mapping.wpid where types.type = 'politician' 

但是現在我想知道政治家屬於哪些類型。我知道我必須使用group byhaving條款。但我無法想出這個問題。如何編寫這個查詢?

回答

1

嘗試過濾表:

select p.name, t2.type 
from types t1 
join mapping m1 on m1.guid = t1.guid 
join people p on p.wpid = m1.wpid 
join mapping m2 on p.wpid = m2.wpid 
join types t2 on m2.guid = t2.guid 
where t1.type = 'politician' 
order by 1, 2 

- 列出所有政治家和他們所屬的所有類型。

或者,如果你只是想所有的政客的名單和不同類型的他們屬於,請嘗試:

select p.name, count(*) 
from mapping m1 
join people p on p.wpid = m1.wpid 
join mapping m2 on p.wpid = m2.wpid 
where m1.guid = 1 /* replace 1 with appropriate guid for politicians */ 
group by p.name 
order by 1 
1

必須使用group by來爲一組值(例如接收不同類型的計數或值的總和)提供聚合函數的結果。如果您只需要獲取某人屬於哪組類型,則可以使用這樣的單個查詢。

select name, types 
from people inner join 
(mapping inner join types on mapping.guid = types.guid) 
on people.wpid = mapping.wpid 
where people.wpid in (select people.wpid from people inner join 
(mapping inner join types on mapping.guid = types.guid) 
on people.wpid = mapping.wpid where types.type = 'politician') 

由一組將是有益的知道政治家是多少組到

select name, count(types) 
from people inner join 
(mapping inner join types on mapping.guid = types.guid) 
on people.wpid = mapping.wpid 
where people.wpid in (select people.wpid from people inner join 
(mapping inner join types on mapping.guid = types.guid) 
on people.wpid = mapping.wpid where types.type = 'politician') 
group by name 

編輯:避免在子查詢

如果你知道政治家的GUID小組,你可以做這樣的事情。我沒有測試查詢,但這個想法是使用與映射表的連接與GUID等於政治家GUID

select p.name, count(t.types) 
from people p inner join mapping m1 
on p.wid = m1.wid and m1.guid = [politician guid] 
inner join mapping m2 
on p.wid = m2.wid 
inner join types t 
in m2.guid = t.guid 
+0

感謝。我想我和'group by'混淆了。順便說一句,有可能避免'in'子查詢?人tabel有大約200萬行,這個查詢可能太慢了:( – Sudar

+0

編輯爲這個問題添加解決方案 –