仅显示MySQL中UNION ALL查询的重复项

时间:2017-03-23 02:10:04

标签: mysql sql

我有一个从4 UNIONS收集用户名的查询。如何仅显示该结果中的重复用户? (理想情况下,只显示每个重复一次)。

谢谢!

以下是查询:

(SELECT user1 AS user FROM   friendships WHERE  user2 = 'johnsmith') 
UNION ALL 
(SELECT user2 AS user FROM   friendships WHERE  user1 = 'johnsmith') 
UNION ALL 
(SELECT user1 AS user FROM   friendships WHERE  user2 = 'johndoe') 
UNION ALL 
(SELECT user2 AS user FROM   friendships WHERE  user1 = 'johndoe') 

2 个答案:

答案 0 :(得分:2)

您可以使用聚合:

SELECT user
FROM ((SELECT user1 AS user 
       FROM friendships 
       WHERE user2 = 'johnsmith' 
      ) UNION ALL 
      (SELECT user2 AS user 
       FROM friendships 
       WHERE user1 = 'johnsmith' 
      ) UNION ALL 
      (SELECT user1 AS user 
       FROM friendships 
       WHERE user2 = 'johndoe')
      ) UNION ALL 
      (SELECT user2 AS user 
       FROM friendships 
       WHERE user1 = 'johndoe'
      ) 
     ) u
GROUP BY user
HAVING COUNT(*) > 1;

您可以表达这一点,因此它只会传递一次数据:

SELECT (CASE WHEN user1 = 'johnsmith' THEN user2
             WHEN user2 = 'johnsmith' THEN user1
             WHEN user1 = 'johndoe' THEN user2
             WHEN user2 = 'johndoe' THEN user1
        END) as user
FROM friendships f
WHERE 'johnsmith' in (user1, user2) or 'johndoe' in (user1, user2)
GROUP BY user
HAVING COUNT(*) > 1;

请注意, 完全相同。它只计算'johnsmith''johndoe'之间的友谊。

答案 1 :(得分:1)

SELECT user, count(*) FROM (
(SELECT user1 AS user FROM   friendships WHERE  user2 = 'johnsmith') 
UNION ALL 
(SELECT user2 AS user FROM   friendships WHERE  user1 = 'johnsmith') 
UNION ALL 
(SELECT user1 AS user FROM   friendships WHERE  user2 = 'johndoe') 
UNION ALL 
(SELECT user2 AS user FROM   friendships WHERE  user1 = 'johndoe') ) x
GROUP BY user
HAVING COUNT(*) >= 2

USE GROUP BYHAVING