0

我正在开发类似应用程序的火种,我想获取所有匹配项。在我的匹配表中,每个用户都有自己的条目。所以对于一个匹配项,有两个用户,表中总共有两个条目。

我尝试了如下所示的 sql 查询 select user_id, friend_id from matches where is_match = 1 group by user_id,friend_id

通过查询我得到低于结果`

|--------------------------| 
|user_id|friend_id|is_match|
|--------------------------|
|   23  |    24   |    1   |
|--------------------------|
|   24  |    23   |    1   |
|--------------------------|
|   24  |    25   |    1   |
|--------------------------|
|   25  |    24   |    1   |
|--------------------------|
|   25  |    26   |    1   |
|--------------------------|
|   26   |   25   |    1   |
---------------------------

`

我想要这样的结果。

`

|--------------------------|
|user_id|friend_id|is_match|
|--------------------------|
|   23  |    24   |    1   |
|--------------------------|
|   24  |    25   |    1   |
|--------------------------|
|   25  |    26   |    1   |
|--------------------------|

`

4

2 回答 2

2

您可以通过对user_idfriend_id值进行排序然后仅选择DISTINCT对来获得所需的结果。注意 noGROUP_BY应该是必需的。

SELECT DISTINCT LEAST(user_id, friend_id) AS user1, GREATEST(user_id, friend_id) AS user2
FROM matches
WHERE is_match = 1
于 2019-05-01T06:54:46.380 回答
0

如果每对总是有两行,那么一个简单的解决方案是:

SELECT user_id, friend_id
FROM matches
WHERE is_match = 1 AND
      user_id < friend_id;

SELECT DISTINCT(or )的使用GROUP BY使查询变得更加昂贵。

于 2019-05-01T11:02:23.770 回答