我有以下结构

----------
presences
----------
id
started
ended
user_id

---------
breaks
---------
id
presence_id
started
ended

我需要创建一个SQL查询,返回以下信息
presence_id user_id presence_time breaks_time
其中存在时间是(presence.ended-presence started)-与存在相关的所有中断的总和(break.ended-break.started)
有没有一种通过sql查询获得这些信息的有效方法?
如果你知道如何口若悬河,那就更好了:D
非常感谢!

最佳答案

http://sqlfiddle.com/#!9/650a2/3

SELECT p.id presence_id,
    p.user_id,
    (p.ended-p.started) presence_time ,
    SUM(b.ended-b.started) breaks_time
FROM presences p
LEFT JOIN breaks b
ON p.id = b.presence_id
GROUP BY p.id

更新按用户id分组的同一查询:
http://sqlfiddle.com/#!9/1ce21/1
SELECT
    sub_total.user_id,
    SUM(sub_total.presence_time) ,
    SUM(sub_total.breaks_time)
FROM (
SELECT p.id presence_id,
    p.user_id,
    (p.ended-p.started) presence_time ,
    SUM(b.ended-b.started) breaks_time
FROM presences p
LEFT JOIN breaks b
ON p.id = b.presence_id
GROUP BY p.id) sub_total
GROUP BY sub_total.user_id

关于mysql - 从 child 那里得到时差,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30103658/

10-09 00:37