Mysql查询两列无重复

时间:2016-08-30 06:43:26

标签: php mysql

我有两个名为user1id和user2id的列。 我希望user1id和user2id中存在count count,而不重复userId,例如,如果我的用户id为1: enter image description here

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

SELECT CASE WHEN t.user_id1 > t.userid2 THEN t.user_id1 ELSE t.user_id2 end as user_1,
       CASE WHEN t.user_id1 > t.userid2 THEN t.user_id2 ELSE t.user_id1 end as user_2,
       COUNT(*) as cnt
FROM YourTable t
GROUP BY CASE WHEN t.user_id1 > t.userid2 THEN t.user_id1 ELSE t.user_id2 end ,
         CASE WHEN t.user_id1 > t.userid2 THEN t.user_id2 ELSE t.user_id1 end 

结果将如下所示:

user_id1 , user_id2 , count
   17         1          1
   18         1          3
   19         1          1
   20         1          3

现在你所要做的就是选择你想要的东西,在这种情况下user_id1 , count from ( .. ) where user_id2 = 1

编辑:对于ID为2的用户,请使用:

SELECT CASE WHEN t.user1id > t.user2id THEN t.user1id ELSE t.user2id end as user_1,
       CASE WHEN t.user1id > t.user2id THEN t.user2id ELSE t.user1id end as user_2,
       COUNT(*) as cnt
FROM YourTable t
WHERE 2 IN(t.user1id,t.user2id)
GROUP BY CASE WHEN t.user1id > t.user2id THEN t.user1id ELSE t.user2id end ,
         CASE WHEN t.user1id > t.user2id THEN t.user2id ELSE t.user1id end