以下查询:
Select t1.name
, t1.email
, t1.activated
, count(t2.id) as 'reporter'
, count(t3.id) as 'comments'
, count(t4.id) as 'reported'
from users t1
inner join tickets as t2 on t1.id = t2.reporter_id
inner join comments as t3 on t1.id = t3.user_id
inner join tickets as t4 on t1.id = t4.reported_id
group by name
计数返回所有3个相同的数字
答案 0 :(得分:0)
很高兴看到示例数据,当前结果和预期结果。
但是我猜测是因为您的group by子句不包含t1.email和t1.activated列。
Select t1.name
, t1.email
, t1.activated
, count(t2.id) as 'reporter'
, count(t3.id) as 'comments'
, count(t4.id) as 'reported'
from users t1
inner join tickets as t2 on t1.id = t2.reporter_id
inner join comments as t3 on t1.id = t3.user_id
inner join tickets as t4 on t1.id = t4.reported_id
group by name
, t1.email
, t1.activated
没有示例数据,这很难确定,但是我不认为您的联接可以执行您希望它们执行的操作。您只会为同时拥有“已举报”和“举报者”的用户获得结果,这些票证中至少包含举报该用户的评论。
答案 1 :(得分:0)
count()
返回具有非NULL
值的行数。 id
可能不是NULL
,因此它们返回相同的值。
您的问题的快速解决方案是使用COUNT(DISTINCT
:
Select t1.name, t1.email, t1.activated,
count(distinct t2.id) as reporter,
count(distinct t3.id) as comments,
count(distinct t4.id) as reported
. . .
请勿对列别名使用单引号!仅对字符串和日期常量使用单引号。
请注意,您的查询将永远不会为任何计数返回0
值。而且,这比必要的昂贵。我在这里没有提供更有效的解决方案,因为以上内容回答了您的问题。如果查询还有其他问题,请问一个 new 问题,并提供适当的示例数据,所需的结果以及要执行的操作的说明。