2013-12-13 26 views
0

這可能很簡單,但我無法弄清楚。這裏是我正在使用的表格。計算具有相同記錄集的行

表-A

id other_data 
------------- 
1  blah 
2  foo 
3  bar 

表-B

ref_a ref_c 
------------- 
1  1 
1  2 
2  3 
3  3 

table_c

id name 
---------- 
1 TestA 
2 TestB 
3 TestC 

我想要得到的是這樣的事情,我就指望的行數(表-A )具有相同的子集(table_b)。我也希望能夠從另一個表(來自table_c的名稱)獲取相關數據。

TestA,TestB 1 
TestC  2 

我知道它可能使用分組依據和GROUP_CONCAT,但我無法得到它的工作。

我試過這個,但它不起作用。

SELECT GROUP_CONCAT(DISTINCT table_cname分離器 '')爲 'combo_text',COUNT(DISTINCT table_aid) FROM table_a INNER JOIN table_btable_aid = table_bref_a INNER JOIN table_c on table_cid = table_bref_c GROUP BY table_bref_a

+1

請格式化你的問題更好的(你的例子數據和示例輸出) – apartridge

+0

你還可以請編輯你的問題,包括你嘗試過,沒有工作,每堆棧溢出的[良好的問題準則](http://stackoverflow.com/help/on-topic)? – Derek

回答

2
SELECT a.id, count(a.id) as count, GROUP_CONCAT(name) as names 
FROM table_a a 
JOIN table_b b ON (a.id = b.ref_a) 
JOIN table_c c ON (b.ref_c = c.id) 
GROUP BY a.id 

sqlFiddle demo

根據您的結果想是這樣的

SELECT names, count(count) as count FROM 
    (SELECT a.id, count(a.id) as count, GROUP_CONCAT(name) as names 
    FROM table_a a 
    JOIN table_b b ON (a.id = b.ref_a) 
    JOIN table_c c ON (b.ref_c = c.id) 
    GROUP BY a.id 
)T1 
GROUP BY names 

sqlFiddle demo

+0

謝謝!在我糾正我的問題之前,你得到了正確的答案。 –

相關問題