2014-03-28 53 views
0

我有兩個表:MySQL的加入:獲得與數器件爲每種類型的

1)部分

part_id | part_name 

2)職位

post_id | part_id | type | title | content 

在職位表後有一個三種類型,所以在類型列我把價值(1或2或3)

我想得到表(與計數和加入)像這樣

part_id | part_name | count_posts_type1 | count_posts_type2 | count_posts_type3 

如何用mysql做到這一點?

例如:

enter image description here

+1

這兩張表格的共同點是什麼? – mesutozer

+0

常見的是part_id我修好了 –

+0

我加了一個例子,結果我需要 –

回答

2

如果您擁有有限的類型列表,請執行此操作。

然後左連接得到沒有帖子的部分結果(並且合併結果爲0而不是null),在這裏我們繼續。

select 
pa.part_id, pa.part_name, 
coalesce(sum(case when po.type = 1 then 1 else 0 end), 0) as count_posts_type1, 
coalesce(sum(case when po.type = 2 then 1 else 0 end), 0) as count_posts_type2, 
coalesce(sum(case when po.type = 3 then 1 else 0 end), 0) as count_posts_type3 
from parts pa 
left join posts po on po.part_id = pa.part_id 
group by pa.part_id, pa.part_name 
+0

這個很好用,謝謝很多^ _ ^ –

0

你試過類似(只是開玩笑,我知道你嘗試過什麼)是這樣的:是一個相當普遍的方式,當使用帶有案件總和

SELECT 
    parts.part_id, 
    parts.part_name, 
    COUNT(t1.post_id) AS count_posts_type1, 
    COUNT(t2.post_id) AS count_posts_type2, 
    COUNT(t3.post_id) AS count_posts_type3 
FROM posts 
    RIGHT JOIN part ON posts.part_id=parts.part_id 
    INNER JOIN (SELECT post_id FROM posts WHERE type=1) as t1(post_id) ON posts.post_id = t1.post_id 
    INNER JOIN (SELECT post_id FROM posts WHERE type=1) as t2(post_id) ON posts.post_id = t2.post_id 
    INNER JOIN (SELECT post_id FROM posts WHERE type=1) as t3(post_id) ON posts.post_id = t3.post_id