Mysql查询LEFT JOIN意外结果

时间:2016-05-13 21:17:26

标签: mysql select join

mysql使用左连接的SELECT查询不会产生我期望的结果。 我希望有人可以告诉我或指出我正确的方向,

我正在尝试构建一个查询,我从“users”表中获取所有用户名 从主表中获取他们为特定日期花费的所有时间的总和。我已经使用了左连接,但我没有按预期得到结果。

    Sub Joining()
    Dim N As Long, i As Long, r1 As Range, r2 As Range
 Dim z As Long
 Dim arr() As Variant
 z = 1

With Activesheet
    N = .Cells(Rows.Count, "A").End(xlUp).Row
    For i = 1 To N
        If .Cells(i, "B").Value Like "Summary*" Then
            arr = .Range(.Cells(i, "A"), .Cells(i, "H")).Value
            .Cells(z, "B").Value = Join(arr, " ")
            z = z + 1
        End If
    Next i
End With

主表

 SUM(m.time_spent) as sum_total_time
 FROM master as m
  LEFT OUTER JOIN users as u ON u.user_id = m.user_id
   WHERE m.date_created >= '2016-05-09'
  AND m.date_created <= '2016-05-13'
 GROUP BY name
 ORDER BY name

用户表

master_id       user_id         time_spent               date_created
1                     1              40                   2016-05-01
2                     2             36                   2016-05-02
3                     3              56                   2016-05-03
4                     2             33                   2016-05-03
5                     1              32                   2016-05-05
nth                 nth       nth number                    nth date

我希望输出结果如下所示:

user_id            first_name            last_name
1                     James                 Green
2                     Robert                 Cox 
3                    Andy                    Roger
etc                   etc                    etc

2 个答案:

答案 0 :(得分:0)

您必须直接从主表中选择数据,逐个用户地计算总和。然后,您可以将此结果与用户表连接,以获取有关该用户的所有信息。

答案 1 :(得分:0)

可能是日期转换问题..

 SUM(m.time_spent) as sum_total_time
 FROM master as m
  LEFT OUTER JOIN users as u ON u.user_id = m.user_id
   WHERE m.date_created >=STR_TO_DATE( '2016-05-09', '%Y-%m-%d)

和/或你还有不完整的sql

SUM(m.time_spent) as sum_total_time
 FROM master as m
  LEFT OUTER JOIN users as u ON u.user_id = m.user_id
   WHERE m.date_created >= '2016-05-09'
  AND m.date_created  // this condition don't match with nothing.. 
                      // could be you forgot a part 

更新1
如果你想要用户总计那么

   select u.id,   u.name, SUM(m.time_spent) as sum_total_time
   FROM master as m
   Inner  JOIN users as u ON u.user_id = m.user_id
   WHERE m.date_created >=STR_TO_DATE( '2016-05-09', '%Y-%m-%d)
   AND m.date_created <= =STR_TO_DATE('2016-05-13'', '%Y-%m-%d)
   Group by u.id