在一个查询中将两个表分组

时间:2017-09-29 19:40:25

标签: mysql select group-by

有没有办法在同一时间选择和分组两个表?

我的查询:

SELECT t1.id, t1.estimated_sum_all, t1.story_point_sum_all, 
 t1.time_spent, t2.id, t2.time_spent FROM
 burndown_snap_all t1, status_history_hours t2 WHERE t1.project_id = 72 
 AND t2.project_id = 72 group by t1.id

结果:

enter image description here

问题是我想将第二个表((status_history_hours))分组以在一个查询中获得正确的结果。

样品:

我有两张桌子:

SELECT * FROM `burndown_snap_all` WHERE project_id=72 

结果: enter image description here

SELECT * FROM `status_history_hours` WHERE project_id=72 

结果:

enter image description here

我想要做的是将第二列加入结果(time_spent)

1 个答案:

答案 0 :(得分:0)

是的,您可以将所有需要的表分组

但是group by用于聚合函数,例如sum()或count(),所以你可以

SELECT 
    t1.id
    , t1.estimated_sum_all
    , t1.story_point_sum_all
    , sum(t1.time_spent)
    , t2.id
    , sum(t2.time_spent ) 
FROM  burndown_snap_all t1
INNER JOIN status_history_hours t2 ON  t1.project_id = 72  AND t2.project_id = t1.project_id
group by t1.id  , t1.estimated_sum_all , t1.story_point_sum_all , t2.id

否则,如果不需要进行聚合,你需要避免重复的价值,你应该使用distinct而不是group

SELECT disticnt 
    t1.id
    , t1.estimated_sum_all
    , t1.story_point_sum_all
    , t1.time_spent
    , t2.id
    , t2.time_spent 
FROM  burndown_snap_all t1
INNER JOIN status_history_hours t2 ON  t1.project_id = 72  AND t2.project_id = t1.project_id