我有2个表,follow
和following
关注
+---------+----------------+
| 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-如果类别重复,则可以是follow
或following
。没关系。
条件4-follow_user_id
为target_user_id
,following_user_id
为target_user_id
在这种情况下,我是否必须使用join?还是工会?
任何建议,非常感谢。
谢谢!
答案 0 :(得分:1)
只需使用union
和group 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)