表2中的SQL COUNT记录加入

时间:2010-04-08 08:01:26

标签: sql mysql select join count

使用MySQL,我有三个表:

项目

ID  name
1   "birthday party"
2   "soccer match"
3   "wine tasting evening"
4   "dig out garden"
5   "mountainbiking"
6   "making music"

批次

ID  projectID  templateID  when
1   1          1            7 days before
2   1          1            1 day  before
3   4          2           21 days before
4   4          1            7 days before
5   5          1            7 days before
6   3          5            7 days before
7   3          3           14 days before
8   5          1           14 days before

模板

ID  name  message
1   inf1  "Hi, I'd like to invite ..."
2   for1  "Dear Sir, Madam, ..."
3   can1  "Can you please ..."
4   inf2  "Would you like to ..."
5   all1  "To all dear friends ..."
6   inf3  "Does any of you guys ..."

我想显示一个模板表和他们使用的项目数。 所以,结果应该是(更新!):

templateName  projectCount
inf1          3
for1          1
can1          1
inf2          0
all1          1
inf3          0

我已尝试使用各种JOIN进行各种SQL查询,但我想这对我来说太复杂了。是否可以使用单个SQL语句获得此结果?

5 个答案:

答案 0 :(得分:2)

SELECT t.name templateName, COUNT(DISTICT b.projectID) projectCount
FROM templates t
LEFT OUTER JOIN batches b ON t.ID = b.templateID
GROUP BY t.ID, t.name
ORDER BY t.ID

答案 1 :(得分:1)

Select TemplateId,
       Count(distinct projectId) as ProjectCount,
FROM batches 
Group By TemplateId

我希望这应该有用。

我们需要与样本数据截然不同,我可以看到相同的模板和项目有多行......

答案 2 :(得分:0)

你试过这样的事吗: -

SELECT TemplateId, COUNT(ProjectId) AS ProjectCount FROM Batches GROUP BY TemplateId

答案 3 :(得分:0)

从您上面给出的o / p所需样本我假设您想要将templateId的数量作为projectCount

select templateID, count(templateID) as projectCount from batches group by templateID
编辑(编辑后编辑)

select t.name as templateName, count(b.templateID) as projectCount from batches b, templates t where b.templateID=t.id group by t.id

答案 4 :(得分:0)

我不确定mySql语法,但是应该这样做:

SELECT t.name as templateName, COUNT(DISTINCT b.projectID) as projectCount
FROM batches b
INNER JOIN templates t
  ON b.templateId = t.ID
GROUP BY t.name