我有两个数据库。这些是core
和push
。
这是来自subs
数据库的core
表:
+----+---------+----+----+-----+
| id | service | ad | op | act |
+----+---------+----+----+-----+
| 1 | CHO | 96 | x | 1 |
| 2 | CHO | 98 | x | 1 |
| 3 | DANG | 96 | x | 1 |
| 4 | HOORAY | 96 | x | 1 |
| 5 | CHO | 98 | x | 1 |
| 6 | DANG | 96 | x | 1 |
+----+---------+----+----+-----+
这是buff
数据库中的push
表:
+----+---------+-------+
| id | service | sub |
+----+---------+-------+
| 1 | DANG | daily |
| 2 | HOORAY | daily |
| 3 | DANG | daily |
+----+---------+-------+
我想计算subs
和buff
。我对subs:
select service, ad, op, count(1) as sub where act=1 group by service,ad,op;
RESULT:
+---------+----+----+-----+
| service | ad | op | sub |
+---------+----+----+-----+
| CHOO | 96 | x | 1 |
| CHOO | 98 | x | 2 |
| HOORAY | 96 | x | 1 |
| DANG | 96 | x | 2 |
+---------+----+----+-----+
这是buff
的查询:
select service, count(1) as pushed
from buff a where sub = 'daily'
group by service;
RESULT:
+---------+---------+
| service | pushed |
+---------+---------+
| HOORAY | 1 |
| DANG | 2 |
+---------+---------+
所以,我的问题是如何从两个不同的数据库中加入这些表? 这是我期望的结果:
+---------+----+----+-----+--------+
| service | ad | op | sub | pushed |
+---------+----+----+-----+--------+
| CHOO | 96 | x | 1 | 0 |
| CHOO | 98 | x | 2 | 0 |
| HOORAY | 96 | x | 1 | 1 |
| DANG | 96 | x | 2 | 2 |
+---------+----+----+-----+--------+
答案 0 :(得分:0)
一种选择是将两个当前子查询连接在一起。我在下面使用了完整的外部联接,因为我们希望处理服务可能只出现在subs
或buff
表中的可能性,但不能同时出现两者。
SELECT t1.service,
t1.ad,
t1.op,
t1.sub,
COALESCE(t2.pushed, 0) AS pushed
FROM
(
SELECT service, ad, op, COUNT(*) AS sub
FROM subs
WHERE act = 1
GROUP BY service,ad,op
) t1
LEFT JOIN
(
SELECT service, COUNT(1) AS pushed
FROM buff a
WHERE sub = 'daily'
GROUP BY service
) t2
ON t1.service = t2.service
UNION
SELECT t2.service,
COALESCE(t1.ad, -1),
COALESCE(t1.op, -1),
COALESCE(t1.sub, -1),
t2.pushed
FROM
(
SELECT service, ad, op, COUNT(*) AS sub
FROM subs
WHERE act = 1
GROUP BY service,ad,op
) t1
RIGHT JOIN
(
SELECT service, COUNT(1) AS pushed
FROM buff a
WHERE sub = 'daily'
GROUP BY service
) t2
ON t1.service = t2.service
答案 1 :(得分:0)
使用数据库名称作为带有点的表名前缀,我不检查下面的句子,它只显示了这个想法:
SELECT service, ad, op, count(1) AS sub FROM core.subs AS t1
LEFT JOIN push.buff AS t2 ON t1.service=t2.service WHERE t1.act=1
AND sub = 'daily' GROUP BY t1.service,t1.ad,t1.op