我正在编写一个查询,我正在尝试计算报表和分配表中的记录总数,同时从主表组中检索信息。组具有主键ID,其作为gid保存在其他表中。这是查询:
SELECT `group`.`id` AS `gid`
, `group`.`name` AS `g_name`
, COUNT(`report`.`id`) AS `reports`
FROM `group`
LEFT OUTER JOIN `report` ON `report`.`gid` = `group`.`id`
LEFT OUTER JOIN `assignment` ON `assignment`.`gid` = `group`.`id`
WHERE `group`.`active` = 0
ORDER BY
`group`.`name`;
我的问题是每当我执行此操作时,即使他们的多个组也只返回一条记录。
提前致谢。
答案 0 :(得分:3)
嗯,你的查询远非正确:)首先,你不应该有没有count
子句的聚合函数(在这种情况下是group by
)。现在,即使您有该子句,查询也会汇总信息,您需要两者:同一查询中的详细信息和摘要。我建议使用2个单独的查询来检索此信息,但如果您希望仅在一个查询中混合信息(详细信息以及"报告和分配表中的记录总数"),请尝试以下操作查询:
SELECT
`group`.id AS gid,
`group`.name AS g_name,
(SELECT COUNT(*) from report) as ReportTotalCount,
(SELECT COUNT(*) from assignment) as AssignmentTotalCount,
FROM `group`
WHERE `group`.`active` = 0
LEFT OUTER JOIN report ON report.gid = `group`.id
LEFT OUTER JOIN assignment ON assignment.gid = `group`.id
ORDER BY `group`.name;
我知道我可以理解你正在寻找什么,但这可能会让你知道如何获得你期望的结果。
答案 1 :(得分:0)
在您的查询中看不到任何明显的限制它返回一条记录的内容。
您将不得不将其分解以查看问题与现有数据的对比情况。
那么acitive = 0的多少个组,多个具有相应赋值记录的组等等。
答案 2 :(得分:0)
也许会有所帮助:
SELECT
groupid,
groupname,
reports,
assignments,
FROM
(SELECT group.id, group.name, COUNT(*) AS reports from group
INNER JOIN report ON (report.gid = group.id)
WHERE group.active = 0
GROUP BY group.id ) AS ReportForGroup
CROSS JOIN
(SELECT group.id AS groupid, group.name AS groupname, COUNT(*) AS assignments from group
INNER JOIN assignmentON (assignment.gid = group.id)
WHERE group.active = 0
GROUP BY group.id ) AS AssignmentForGroup
ON (ReportForGroup.groupid = AssignmentForGroup.groupid)
ORDER BY groupname;
我无法检查它,所以如果LEFT JOIN返回COUNT(*)0或1.如果它返回0只需将INNER更改为LEFT并在两个查询之间使用INNER JOIN