有三个表,它们之间的关系:
'任务'由雇主(uid)'
创建'执行'完成由员工(uid)'并匹配'任务(tid)'
tid | name | employer ========================== 1 | Hello world | 1 2 | Eat food | 1 3 | Swimming | 2
uid | name ============= 1 | Salmon 2 | Bird 3 | Pig
eid | task | employee ====================== 1 | 1 | 2 2 | 1 | 2 3 | 2 | 3 4 | 1 | 3 5 | 2 | 2
然后我做了一些询问。
SELECT T1.tid,
T1.name AS taskName,
T1.employer AS employerUid,
T2.name AS employerName,
COUNT(T3.*)
FROM task T1, user T2, execution T3
WHERE T1.employer = T2.uid
AND T1.tid = T3.task
AND T1.tid = ( Here can input the task id )
我的问题:
我输入'T1.tid = 1'
进行查询,我希望获得COUNT()
'3'
的结果。
eid | task | employee ====================== 1 | 1 | 2 ---- I want 2 | 1 | 2 ---- I want 3 | 2 | 3 4 | 1 | 3 ---- I want 5 | 2 | 2
但是SQL总是返回'5'
,我想'5'
表示表执行总行。
如何在上述情况下获得COUNT
?
谢谢大家。
答案 0 :(得分:1)
使用JOIN而不是尝试将所有内容都插入到WHERE子句中。
SELECT T1.tid,
T1.name AS taskName,
T1.employer AS employerUid,
COUNT(*)
FROM task T1
JOIN execution T3 ON T3.task = T1.tid
JOIN user T2 ON T3.eid = T2.uid
WHERE T1.tid = ( Here can input the task id )
请注意,您可以完全不使用JOIN用户T2,因为在计算时它与您无关。我在计算时也省略了显示员工编号,因为会有很多这样的员工。如果需要,您还可以将WHERE更改为GROUP BY并显示单个查询中所有tid的计数。
答案 1 :(得分:1)
试试这个
select T1.tid as task, count(T2.id) as employee
from task T1
inner join execution T3 on T3.task = T1.tid
inner join employee T2 on T3.employee = T2.eid
group by T1.id
order by T1.id;
我假设您想要计算员工T2而不是执行T3?
很抱歉,如果我现在无法访问MySQL,那么
答案 2 :(得分:0)
如果您在select中有一个聚合函数(如COUNT),则必须包括您要如何对要聚合的记录进行分组。通常情况下,您的查询没有GROUP BY子句会产生错误,而不是奇怪的结果。也许MySQL在这方面更宽容。
GROUP BY T3.task