MySQL计数出现次数

时间:2014-06-19 04:27:18

标签: mysql sql

我有这两张桌子:

Category:
cat_id|cat_type
   1  |    a
   2  |    b
   3  |    c
   4  |    d

并且

Meta:
met_id|met_name|user_id|met_type
   10 |  bla   |   2   |    1
   11 | blabla |   4   |    2
   12 |  foo   |   1   |    3
   13 | blafoo |   3   |    4
   14 | foofoo |   5   |    4

我怎样才能归还这样的东西?

cat_type|occurences
  a   |     1
  b   |     1
  c   |     1
  d   |     2

met_type是来自Category的外键。

2 个答案:

答案 0 :(得分:2)

SELECT c.cat_type
     , COUNT(m.met_type) AS  occurrences 
FROM categoty c LEFT JOIN meta m ON c.cat_id = m.met_type 
GROUP BY c.cat_type

答案 1 :(得分:0)

SELECT cate.cat_type as 'cat_id', count(meta.met_type) as 'occurences'
FROM Category cate
LEFT JOIN Meta meta on(cate.cat_id = meta.met_type)
GROUP BY meta.met_type