Using 2 rows with matching columns to show 1 result

Yaseen Hussain :

I have a MYSQL table as example below

id    user_id    opponent_id 
1     1          2
2     2          1
3     3          16
4     16         3

As you see the above table the user_id and opponent_id are relative. I want to write a query which will combine the relative rows and give me a single row instead.

Expected output

id    user_id    opponent_id 
1     1          2
3     3          16

What I have tried so far is using groups but that isn't working. (Codeigniter)

        $this->db->select('e.*'); 
        $this->db->from('entries e');
        $this->db->group_by('e.user_id, e.opponent_id');
        $query = $this->db->get();
        $row = $query->result();

Any tips and help will be much appreciated.

Akina :
SELECT MIN(id) id,
       LEAST(user_id, opponent_id) user_id,
       GREATEST(user_id, opponent_id) opponent_id
FROM entries 
GROUP BY LEAST(user_id, opponent_id),
         GREATEST(user_id, opponent_id)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=174148&siteId=1