0

所以我有以下查询:

'SELECT *, upload.id AS id, report.id AS report_id, (SELECT COUNT(*) 
    FROM upload WHERE report.upload_id = upload.id) AS nums FROM upload 
    LEFT JOIN report ON upload.id=report.upload_id WHERE private="0" '

我对如何计算每次上传的报告有疑问。此查询需要计算给定上传的所有报告,并在获取时返回所有上传。由于某种原因,每次插入新报告而不是添加到总数中时,我都会重复上传。见下图:

在此处输入图像描述

请注意,对于与给定上传相关的每个报告,console (1).png 如何显示三次......真的我希望它显示一次,然后侧面的计数应该是(3)。任何帮助将非常感激!!

4

4 回答 4

0

选择 count(upload.id),report.id from report,上传 LEFT JOIN report ON upload.id=report.upload_id WHERE private="0" group by report.id

于 2012-12-25T21:16:35.603 回答
0

如果您只需要每次上传的报告数量,则不需要加入它们,您可以这样做:

SELECT upload.*, 
      (SELECT COUNT(*) FROM report WHERE report.upload_id = upload.id) AS nums 
FROM upload 

或者你可以这样做:

SELECT upload.id, upload.name, count(*) as nums
FROM upload 
  INNER JOIN report ON report.upload_id = upload.id
GROUP BY upload.id, upload.name

这将返回所有带有报告的上传。要获取包含或不包含报告的所有上传,您需要左连接:

SELECT upload.id, upload.name, count(report.id) as nums
FROM upload 
  left JOIN report ON report.upload_id = upload.id
GROUP BY upload.id, upload.name

这是一个带有查询的SQL Fiddle 。

于 2012-12-25T21:11:01.730 回答
0

用于测试的SQL Fiddle 。

只需使用左连接并计算report.upload_ids

select u.filename, u.filesize, COUNT(r.upload_id) as reports
from upload u
left join report r on u.id=r.upload_id
group by u.id, u.filename, u.filesize

我漏掉了where private = "0",因为你没有指定它属于哪里。

于 2012-12-25T22:27:36.713 回答
0
SELECT 
  upload.id, 
  upload.name, 
  count(1) as nums
FROM 
  upload 
LEFT OUTER JOIN 
  report ON
  report.upload_id = upload.id
GROUP BY 
  upload.id,
  upload.name
于 2012-12-25T21:51:30.547 回答