MySQL查询列中的计数

时间:2012-07-24 15:09:48

标签: mysql count

我有两个表l & C,它们由两个字段l.mIDc.mID链接,c表包含三种类型的记录cs, ls, & vs,我的查询需要选择所有来自l的记录和作为查询的一部分有三列显示cs, ls & vs;

的总计

到目前为止,我正在使用外部联接:

SELECT l.*, COUNT(*) FROM l LEFT OUTER JOIN c ON c.mID = l.mID WHERE l.mID = 2

但是这只是添加了一个完整的列,任何帮助都会非常感谢。

2 个答案:

答案 0 :(得分:2)

您可以在计数中使用CASE语句:

select
  l.*
  ,COUNT(CASE WHEN c.type = 'cs' then 1 END) as cscount
  ,COUNT(CASE WHEN c.type = 'ls' then 1 END) as lscount
  ,COUNT(CASE WHEN c.type = 'vs' then 1 END) as vscount
from l
left outer join c on c.mID = l.mID
where l.mID = 2

答案 1 :(得分:1)

select
  l.*
  ,sum(c.type = 'cs') as cscount
  ,sum(c.type = 'ls') as lscount
  ,sum(c.type = 'vs') as vscount
from l
left outer join c on c.mID = l.mID
where l.mID = 2