0

我在 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 结果可以是零或空):

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

1 回答 1

5

您需要一个Left Outer Join,它将从左表中获取行,如果它与右表不匹配,那么您将获得 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
于 2012-10-03T04:41:14.930 回答