我为我的客户端编码网络应用程序,并与从数据库中选择最新修订报告的问题。
SELECT
raports.*,
r1.*,
users.*,
(SELECT COUNT(*) FROM changes WHERE changes.changes_raports_id = raports.raports_id) as changes,
(SELECT changes.changes_date FROM changes WHERE changes.changes_raports_id = raports.raports_id ORDER BY changes.changes_date DESC LIMIT 1) as last_change,
(SUM(injuries.injuries_min_procent) / COUNT(injuries_to_raports.injuries_to_raports_id)) as min,
(SUM(injuries.injuries_max_procent) / COUNT(injuries_to_raports.injuries_to_raports_id)) as max
FROM raports
LEFT JOIN users
ON users.users_id = raports.raports_users_id
LEFT JOIN changes
ON changes.changes_raports_id = raports.raports_id
LEFT JOIN raports_to_changes r1
ON r1.raports_to_changes_raports_id = raports.raports_id
LEFT JOIN injuries_to_raports
ON injuries_to_raports.injuries_to_raports_raports_id = r1.raports_to_changes_raports_id
LEFT JOIN injuries
ON injuries_to_raports.injuries_to_raports_injuries_id = injuries.injuries_id
WHERE r1.raports_to_changes_changes_id = (SELECT max(raports_to_changes_changes_id) FROM raports_to_changes r2 WHERE r2.raports_to_changes_raports_id = r1.raports_to_changes_raports_id)
GROUP BY raports.raports_id ORDER BY raports.raports_id ASC;
在最大值和最小值列中,我没有正确的平均受伤数。当我检查它并计算所有受伤数时,我有36次受伤,而实际数字是2,但我有18次修订。因此,逻辑是我循环了所有修订数的计数,但我只想要最新的
我试着修改WHERE语句和更多的LEFT JOIN,但没有任何帮助。
有人能修复那个代码吗?
先谢谢你
1条答案
按热度按时间8zzbczxx1#
根据查询所揭示的线索,数据模型可能如下所示:
select
列表显示您需要:reports_id
的users
信息1.在
raports_id
级别聚合injuries_min_procent
和injuries_max_procent
。(请参见cte_raport_injuries
)1.一个
raports_id
的changes
的数量(参见cte_raport_changes
)raports_id
的最后一个change_date
(请参见cte_raport_changes
)根据问题中透露的信息,我不确定是否需要
raports_of_changes
,所以现在我将忽略它。结果如下所示:
所以我想问你的是,你需要
reports_to_changes
中的什么,它与其他人之间的关系是什么?为了进一步参与社区,你可能想以文本格式分享以下信息: