简体   繁体   English

SQL Join问题返回NULL值

[英]SQL Join issue returning NULL values

I am having trouble running a query over three tables: 我无法对三个表运行查询:

users, user_teams, user_messages 用户,user_teams,user_messages

I wish to create a report where a line manager can see the total for incoming mail and outgoing mail for all members of their team. 我希望创建一个报告,在此报告中,直属经理可以查看其团队中所有成员的传入和传出邮件总数。 The query is to show zero values for a user if there are no outgoing or incoming. 如果没有传出或传入,查询将为用户显示零值。

My tables are as follows: 我的表格如下:

users
------
uid
forename
surname

user_teams
-------------
id
manager_id
member_id

user_messages
-------------
id
outgoing
incoming
uid
msg_date

Both manager_id and member_id relate to the uid field of users. manager_id和member_id都与用户的uid字段相关。 There is a one to many relationship between managers and users. 管理者和用户之间存在一对多的关系。

My query so far is this: 到目前为止,我的查询是:

SELECT u.uid, u.forename, u.surname,
SUM(IF(m.outgoing=0 ,1,0)) AS total_outgoing,
SUM(IF(m.incoming>0 ,1,0)) AS total_incoming,
FROM users u
INNER JOIN user_messages m
ON m.uid=u.uid AND m.msg_date>='2012-09-01' AND m.msg_date<='2013-08-31'
RIGHT JOIN user_teams ut ON ut.member_id=u.uid
WHERE ut.leader_id=?
GROUP BY u.uid
ORDER BY u.surname ASC 

This functions correctly if a user has either sent or received a message. 如果用户已发送或接收消息,此功能将正常运行。 However, if the SUM for both fields is zero, I recieve NULL for uid, forename and surname. 但是,如果两个字段的SUM均为零,则uid,forename和surname为NULL。

使用LEFT JOIN user_messages m INNER JOIN user_messages m没有消息时,通常会收到消息(uid,forename和INNER JOIN user_messages m为NULL)。

使用COUNT而不是SUM或将IFNULL子句添加到传出和传入选择中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM