2011-02-28 52 views
0

表一個MySQL的選擇行和計數每個連接的不同行

product c 
========================================== 
sample_1 Line 
sample_1 LLk 
sample_1 LLk 
sample_1 LLk 
sample_1 LLk 
sample_2 LLk 
sample_3 LLk 
sample_2 LLk 
sample_3 LLk 
sample_2 Line 

加上這個表中的兩個

a h  r 
========================================== 
LLk sample_1 gw 
LLk sample_2 okp 
LLk sample_3 ijof 
Line xe  rr3 
LLk sample_4 gr2 
Line xx2  o3 

最後會是這樣..

基於從表2,其中在搜索a = LLk

這是從表1和表2產生的表3

product counts 
============================ 
sample_1 4 
sample_2 1 
sample_3 2 
sample_4 0 

細節鏈接,這個問題 http://pastebin.com/ds0iS4GU

+0

如何'sample_2'數爲1的答案?我認爲計數應該是b 2 ..將你的plz寫出確切的條件 – diEcho 2011-02-28 06:46:13

回答

0

你在找這樣的事情?

select product, count(a) 
from table_two 
inner join table_one on product=h and c=a 
where a = 'LLk' 
group by product 
+0

你的解決方案不會返回'sample_4'。 – 2011-03-10 02:58:19

+0

哎呦沒有看到sample_4,那應該只需要一個左連接,看起來好像已經回答了它吧 – P4ul 2011-03-14 21:09:22

1

這會給你你正在尋找

select h, count(t1.product) from t2 LEFT JOIN t1 ON t1.c=t2.a and t1.product=t2.h where t2.a='LLk' group by t2.h