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構文を使用してこれらのテーブルを「INNERJOIN」すると、次のようになります。
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の結果はゼロまたはNULLになる可能性があります):
+--------------+--------------------------+--------+---------+
| Username | Message | StatOK | StatBAD |
+--------------+--------------------------+--------+---------+
| jamesbond | I need some help | 2 | 1 |
| jamesbond | Mission accomplished | NULL | NULL |
+--------------+--------------------------+--------+---------+