具有连接的行的总和

时间:2011-10-05 15:20:39

标签: mysql sql

MySQL problem

这是当前的表格布局。

  • 有3条腿
  • 每条腿有2个点,其中is_start = 1是腿的起点,而is_start是腿的末端。
  • 当用户在某个位置登记时,会创建points_user中的条目。

在这个应用程序中,你有多条腿有2个点,其中一个标记腿的开始,另一个标记腿的末端。因此,用户(id = 2)Leg(id = 1)的总和为points_userscreated其中points_usersleg_id = 1和points_usersuser_id = 2和points_usersis_start = 0减去points_users,其中is_start = 1(其他参数保持不变)。这只是一条腿。

我想要的是总结每条腿的所有时间差异,我们得到这样的数据:

| User.id | User.name | total_time |
| 1       | John      | 129934     |

任何人都知道我如何加入这些表并按用户分组总结?

(不,这不是家庭作业)

据我所知:

SELECT
( `end_time` - `start_time` ) AS `diff`
FROM
(
    SELECT SUM(UNIX_TIMESTAMP(`p1`.`created`)) AS `start_time`
    FROM `points_users` AS `pu1`
    LEFT JOIN `points` AS `p1` ON `pu1`.`point_id` = `p1`.`id`
    WHERE `p1`.`is_start` = 1
) AS `start_time`,
(
    SELECT SUM(UNIX_TIMESTAMP(`pu2`.`created`)) AS `end_time`
    FROM `points_users` AS `pu2`
    LEFT JOIN `points` AS `p2` ON `pu2`.`point_id` = `p2`.`id`
    WHERE `p2`.`is_start` = 0
) AS `end_time`

2 个答案:

答案 0 :(得分:0)

编辑:现在添加了points表,我可以看到您尝试查询。

最简单的方法是将points_users加入到自身:

select leg_start.user_id, sum(leg_end.created - leg_start.created)
from points_users leg_start
join points_users leg_end on leg_start.user_id = leg_end.user_id
    and leg_start.leg_id = leg_end.leg_id
join points point_start on leg_start.point_id = point_start.id
join points point_end on leg_end.point_id = point_end.id
where point_start.is_start = 1 and point_end.is_start = 0
group by leg_start.user_id

有些人喜欢将这些is_start过滤器放在连接条件中,但因为它是一个内部连接,主要只是一种风格点。如果它是外连接,那么将它们从WHERE移动到JOIN可能会对结果产生影响。

答案 1 :(得分:0)

试试这个:

select users.user_id,
    users.user_name,
    SUM(timeDuration) totalTime
from users
join (
    select 
        pStart.User_id,
        pStart.leg_id,
        (pEnd.created - pStart.created) timeDuration                
    from (select pu.user_id,  pu.leg_id,  pu.created
        from points_users pu
        join points p on  pu.id = p.point_id and pu.leg_id = p.leg_id
        where p.is_start = 1 ) pStart
    join  (select pu.user_id, pu.leg_id,  pu.created
        from points_users pu
        join points p on  pu.id = p.point_id and pu.leg_id = p.leg_id
        where p.is_start = 0 ) pEnd
    on      pStart.user_id = pEnd.user_id
    and     pStart.leg_id = pEnd.leg_id
    ) tt
on users.user_id = tt.user_id
group by users.user_id, users.user_name

子查询获取每个用户/分支的持续时间,然后主查询将它们与每个用户的所有分支相加。