如何在MySQL中正确使用IN?

时间:2017-11-20 06:45:02

标签: mysql

我有一个非常复杂的查询要求,现在我只使用两个表作为演示:

mysql> select * from user_table;
+--------+------+------+
| name   | dep  | uid  |
+--------+------+------+
| frank  | IT   | 1001 |
| jack   | IT   | 1002 |
| Sissel | FA   | 1003 |
| Li     | IT   | 1004 |
| Mok    | PM   | 1005 |
+--------+------+------+

第二个:

mysql> select * from money_log;
+------+-------+
| uid  | money |
+------+-------+
| 1001 |  9989 |
| 1001 |    89 |
| 1001 |   189 |
| 1002 |   389 |
+------+-------+

然后我尝试通过以下方式汇总:

SELECT uid, sum(money) as moneys
FROM money_log
WHERE uid in (
    SELECT uid 
    FROM user_table
    WHERE dep='IT'
) 
GROUP BY uid;

给出了结果。

+------+--------+
| uid  | moneys |
+------+--------+
| 1001 |  10267 |
| 1002 |    389 |
+------+--------+

我的期望是:

+------+--------+
| uid  | moneys |
+------+--------+
| 1001 |  10267 |
| 1002 |    389 |
| 1004 |    0   |
+------+--------+

有什么好办法吗?

1 个答案:

答案 0 :(得分:1)

使用LEFT JOIN代替

select u.uid, coalesce(sum(m.money),0) as money
from user_table u
left join money_log m on u.uid = m.uid  
where u.dep = 'IT'
group by u.uid

nb:确保将表别名包含在每个列引用中。