[英]Mysql query LEFT JOIN unexpected result
mysql SELECT query with left join is not producing the result I am expecting. 带有左联接的mysql SELECT查询未产生我期望的结果。 I hope someone can show me or point me to the right direction, 我希望有人可以向我展示或指向正确的方向,
I am trying to build a query where I get all the users name from the "users" table and fetch the sum of all the time they spent for a particular date from the master table. 我正在尝试建立一个查询,在该查询中我从“用户”表中获取所有用户名,并从主表中获取他们在特定日期花费的所有时间的总和。 I've used the left join but I am not getting the result as expected. 我使用了左联接,但没有得到预期的结果。
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 table 主表
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
users table 用户表
user_id first_name last_name
1 James Green
2 Robert Cox
3 Andy Roger
etc etc etc
I want the output result should look like this: 我希望输出结果应如下所示:
user_id Name sum_total_time
1 James Green 62
2 Robert Cox 69
3 Andy Roger 56
4 Brian Harper 0
5 Angel Lee 0
6 Andrew Martin 55
.....
.....
Nth Name Nth value
You have to select data directly from the master table, group by user and calculate the sum. 您必须直接从主表中选择数据,按用户分组并计算总和。 Then you can join this result with the user table to get all the information about the user. 然后,您可以将此结果与用户表结合起来以获取有关该用户的所有信息。
Could be date conversione issue .. 可能是日期转换问题。
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)
and/or you have also incomplete sql 和/或您也有不完整的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
Update 1 更新1
If you want user totale then 如果您希望用户总数
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.