2

MYSQL Structure:

 ID | USERID | FRIENDID | Type
-------------------------------
 1  |   10   |    20    | Gold
 2  |   20   |    10    | Gold

 3  |   30   |    40    | Silver
 4  |   40   |    30    | Silver

 5  |   50   |    60    | Gold
 6  |   60   |    50    | Gold

 7  |   70   |    80    | Bronze
 8  |   80   |    70    | Bronze

 9  |   90   |   100    | Bronze
10  |  100   |    90    | Bronze

What i want is GROUP (ID 1 & ID 2) and (ID 5 & ID 6) because they are "gold" type, NOT GROUP BY TYPE.

Return Results:

 1. 10 & 20, type:gold. (GROUP)

 3. 30 & 40, type:silver.
 4. 40 & 30, type:silver.

 5. 50 & 60, type:gold. (GROUP)

 7. 70 & 80, type:bronze.
 8. 80 & 70, type:bronze.

 9. 90 & 100, type:bronze.
10. 100 & 90, type:bronze.

How to do that with php query?

Demo: http://sqlfiddle.com/#!2/13bd3/1

3
  • are the ids you want to group static numbers known before hand? Commented Jan 12, 2013 at 18:28
  • if you want type = Gold then why there are more results Commented Jan 12, 2013 at 18:35
  • I'm removing the jquery tag Commented Jan 12, 2013 at 19:07

3 Answers 3

7

What you need to do is to add an additional grouping clause based on the type. When it is 'gold', you get a constant. Otherwise, you use the id:

select least(userid, friendid), greatest(userid, friendid), type
from t
group by least(userid, friendid), greatest(userid, friendid),
         (case when type = 'gold' then 0 else id end)

This does rearrange the order of the ids for non-gold types. If ordering is important, the SQL is a little more complicated:

select (case when type = 'gold' then least(userid, friendid) else userid end),
       (case when type = 'gold' then greatest(userid, friendid) else friendid end),
       type
from t
group by least(userid, friendid), greatest(userid, friendid),
         (case when type = 'gold' then 0 else id end)
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks Gordon! :)
3
SELECT GROUP_CONCAT(friend_id) , type FROM mytable GROUP BY type

Demo

1 Comment

Although this may not be the correct answer for this specific situation, but the group_concat saved my time.
0

Try this:

SELECT id, userid, friendid, type 
FROM (SELECT id, userid, friendid, type, 
             IF(LOWER(type) = 'gold', IF(@lasttype=(@lasttype:=TYPE), @auto, @auto:=@auto+1), @auto:=@auto+1)  indx 
      FROM tablename, (SELECT @auto:=1, @lasttype:=0) a 
      ORDER BY id) a 
GROUP BY indx;

Comments

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.