如何在内部显示NULL或ZERO在两个不同的数据库上加入这两个表?

时间:2012-10-03 04:38:46

标签: mysql

我在2个不同的数据库上有2个表:

db1.table1

+--------------+--------------------------+
| Username     | Message                  |
+--------------+--------------------------+
| jamesbond    | I need some help         |
| jamesbond    | I need some help         |
| jamesbond    | I need some help         |
| jamesbond    | Mission accomplished     |
+--------------+--------------------------+

db2.table2

+--------------------------+--------------+
| Message                  | Status       |
+--------------------------+--------------+
| I need some help         | Ok           |
| I need some help         | Ok           |
| I need some help         | Bad          |
+--------------------------+--------------+

当我使用这种SQL语法“INNER JOIN”这些表时:

SELECT A.Username, A.Message
SUM(CASE WHEN `status` = 'Ok' THEN 1 ELSE 0 END) AS StatOK,
SUM(CASE WHEN `status` = 'Bad' THEN 1 ELSE 0 END) AS StatBAD
FROM db1.table1 as A
INNER JOIN db2.table2 as B 
ON A.Message = B.Message
WHERE A.Username = 'jamesbond'
GROUP BY A.Username, A.Message

我得到了这个结果:

+--------------+--------------------------+--------+---------+
| Username     | Message                  | StatOK | StatBAD |
+--------------+--------------------------+--------+---------+
| jamesbond    | I need some help         | 2      | 1       |
+--------------+--------------------------+--------+---------+

如何得到这样的结果(DB2上没有状态的消息仍然出现,但SUM结果可以是ZERO或NULL):

+--------------+--------------------------+--------+---------+
| Username     | Message                  | StatOK | StatBAD |
+--------------+--------------------------+--------+---------+
| jamesbond    | I need some help         | 2      | 1       |
| jamesbond    | Mission accomplished     | NULL   | NULL    |
+--------------+--------------------------+--------+---------+

1 个答案:

答案 0 :(得分:5)

你需要一个Left Outer Join,它会从Left表中获取行,如果它与Right表不匹配,那么你将获得NULL。

SELECT A.Username, A.Message
SUM(CASE WHEN `status` = 'Ok' THEN 1 ELSE 0 END) AS StatOK,
SUM(CASE WHEN `status` = 'Bad' THEN 1 ELSE 0 END) AS StatBAD
FROM db1.table1 as A
LEFT OUTER JOIN db2.table2 as B 
ON A.Message = B.Message
WHERE A.Username = 'jamesbond'
GROUP BY A.Username, A.Message