Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL GROUP BY multiple columns and fields

I've tried to search answer here, there are few questions are quite similar with my question but i still can't figure out how to GROUP BY below.

MYSQL Structure:

ID | USERID | FRIENDID 
1  |   14   |    65
2  |   65   |    14
3  |   12   |    19
4  |   19   |    12

How to GROUP BY ID 1 & ID 2 and ID 3 & ID 4 with php query?

Result:

1. 14 & 65 
2. 12 & 19
like image 893
richard Avatar asked Mar 25 '26 08:03

richard


1 Answers

SELECT LEAST(USERID, FRIENDID) as x, 
       GREATEST(USERID, FRIENDID) as y
FROM   TableName
GROUP  BY x, y
  • SQLFIddle Demo
like image 99
John Woo Avatar answered Mar 26 '26 20:03

John Woo