3

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
4
  • 2
    You can't use GROUP BY to group by two different values. Do you just want to return the relationships (i.e. user 14 is related to 65)? Commented Jan 12, 2013 at 13:14
  • Hi Ben, i want to display only 1 result, either 14&65 or 65&14. Commented Jan 12, 2013 at 13:17
  • 1
    I understand that - but my question really is how you determine that only those two should be displayed. Is it when one USERID is already existing in FRIENDID? Commented Jan 12, 2013 at 13:18
  • 1
    And you want to return the USERID and FRIENDID fields, rather than the ID? Commented Jan 12, 2013 at 13:21

2 Answers 2

8
SELECT LEAST(USERID, FRIENDID) as x, 
       GREATEST(USERID, FRIENDID) as y
FROM   TableName
GROUP  BY x, y
Sign up to request clarification or add additional context in comments.

Comments

-2
SELECT CONCAT(USERID, ' & ', FRIENDID) FROM table 

7 Comments

It returns 4 rows, when the question asked for only distinct pairs to be returned.
My solution does what you ask - i.e. return the results grouped like this "id1 & id2". Perhaps you need to improve the wording of your question
@BenM nowhere in the question is the word "distinct" mentioned
GROUP BY ID 1 & ID 2 **and** ID 3 & ID 4 <-- that's a direct quote. Heck, he even indicated his desired output...
The wording of this question is still appalling, it even asks for a php query. Any wonder I assumed the desired output was a loose example of the row output, rather than the specific result set...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.