簡體   English   中英

在mysql中執行全外連接

[英]Perform full outer join in mysql

我已經知道我可以使用union在 MySQL 中進行外連接。 我也檢查了這個。 MySQL 中的全外連接

但我想做這樣的事情,我不知道如何使用聯合來實現這一點。

我有數據庫表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    |
+-------------+-----------+---------+-------+

我有以下疑問。

    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;

我想執行外連接或聯合,所以我的結果會是這樣的

+-------------+-----------+------------+------------+--------------+
| 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            | 
+-------------+-----------+------------+------------+--------------+

我怎樣才能做到這一點。 非常感謝任何幫助。

嘗試這個:

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

演示sqlfiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM