连接2个具有不同特征的表

时间:2019-06-13 10:06:19

标签: mysql

我有2个表,followfollowing

关注

+---------+----------------+
| user_id | follow_user_id |
+---------+----------------+
|       1 |              2 |
|       2 |              3 |
|       3 |              4 |
|     100 |             10 |
+---------+----------------+

关注

+---------+-------------------+
| user_id | following_user_id |
+---------+-------------------+
|       1 |                 2 |
|       3 |                 4 |
|       4 |                 6 |
|     200 |               500 |
+---------+-------------------+

我想合并2个表,不要重复。

这是我想要的结果。

+---------+----------------+-----------+
| user_id | target_user_id |  category |
+---------+----------------+-----------+
|       1 |              2 | follow    |
|       2 |              3 | follow    |
|       3 |              4 | follow    |
|       4 |              6 | following |
|     100 |             10 | follow    |
|     200 |            500 | following |
+---------+----------------+-----------+

条件1-删除重复的行

条件2-必须在每个表的名称中添加类别列

条件3-如果类别重复,则可以是followfollowing。没关系。

条件4-follow_user_idtarget_user_idfollowing_user_idtarget_user_id

在这种情况下,我是否必须使用join?还是工会?

任何建议,非常感谢。

谢谢!

1 个答案:

答案 0 :(得分:1)

只需使用uniongroup by,如下所示的SQL:

select 
    user_id,target_user_id,min(tag) as category
from 
(
    select user_id,follow_user_id as target_user_id, 'follow' as tag from follow
    union
    select user_id,following_user_id as target_user_id, 'following' as tag from following
) tmp 
group by 
    user_id,target_user_id 
order by 
    user_id,target_user_id;

+---------+----------------+-----------+
| user_id | target_user_id | category  |
+---------+----------------+-----------+
|       1 |              2 | follow    |
|       2 |              3 | follow    |
|       3 |              4 | follow    |
|       4 |              6 | following |
|     100 |             10 | follow    |
|     200 |            500 | following |
+---------+----------------+-----------+
6 rows in set (0.00 sec)