[英]Perform full outer join in mysql
I already know i can do outer join in MySQL using union
.我已经知道我可以使用
union
在 MySQL 中进行外连接。 I also check this one.我也检查了这个。 Full Outer Join in MySQL
MySQL 中的全外连接
But i want to do something like this and I don't know how can I achieve this using union.但我想做这样的事情,我不知道如何使用联合来实现这一点。
I have db table user_count
as follow.我有数据库表
user_count
如下。
+-------------+-----------+---------+-------+
| meb_id | left_id |right_id |active |
+-------------+-----------+---------+-------+
| 1001 | (NULL) | (NULL) | 1 |
| 1002 | 1001 | 0 | 0 |
| 1003 | 0 | 1001 | 0 |
| 1004 | 1001 | 0 | 0 |
| 1004 | 1002 | 0 | 0 |
+-------------+-----------+---------+-------+
I have queries as follow.我有以下疑问。
SELECT left_id, COUNT(left_id) AS left_count FROM `user_count` GROUP BY left_id
SELECT right_id, COUNT(right_id) AS right_count FROM `user_count` GROUP BY right_id;
SELECT left_id AS meb_id, COUNT(left_id) AS active_left_count FROM `user_count` WHERE active = 1 GROUP BY left_id;
SELECT right_id AS meb_id, COUNT(right_id) AS active_right_count FROM `user_count` WHERE active = 1 GROUP BY right_id;
I want to preform outer join or union so my result will be like this我想执行外连接或联合,所以我的结果会是这样的
+-------------+-----------+------------+------------+--------------+
| meb_id |left_count |right_count |active_left |active_right |
+-------------+-----------+------------+------------+--------------+
| (NULL) | 0 | 0 | 0 | 0 |
| 0 | 1 | 3 | 0 | 0 |
| 1001 | 2 | 1 | 0 | 0 |
| 1002 | 1 | 0 | 0 | 0 |
| 1003 | 0 | 0 | 0 | 0 |
+-------------+-----------+------------+------------+--------------+
How can i do this.我怎样才能做到这一点。 Any help greatly appreciated.
非常感谢任何帮助。
Try this:尝试这个:
select
a.meb_id
,sum(case when a.meb_id = b.left_id then 1 else 0 end) left_count
,sum(case when a.meb_id = b.right_id then 1 else 0 end) right_count
,sum(case when a.meb_id = b.left_id and active = 1 then 1 else 0 end) active_left
,sum(case when a.meb_id = b.right_id and active = 1 then 1 else 0 end) active_right
from (
select meb_id from user_count union
select left_id from user_count union
select right_id from user_count
) a
cross join user_count b
group by a.meb_id
order by a.meb_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.