2

MYSQL 構造:

 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

私が欲しいのは GROUP (ID 1 & ID 2) と (ID 5 & ID 6) です。これらは「ゴールド」タイプであり、 GROUP BY TYPE ではありません

返される結果:

 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.

PHPクエリでそれを行う方法は?

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

4

3 に答える 3

7

あなたがする必要があるのは、タイプに基づいて追加のグループ化句を追加することです。'ゴールド'の場合、定数を取得します。それ以外の場合は、次の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)

これにより、ゴールド以外のタイプのIDの順序が並べ替えられます。順序付けが重要な場合、SQLはもう少し複雑です。

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)
于 2013-01-12T18:45:30.760 に答える
3
SELECT GROUP_CONCAT(friend_id) , type FROM mytable GROUP BY type

デモ

于 2013-01-12T18:30:16.483 に答える
0

これを試して:

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;
于 2013-01-12T18:49:55.187 に答える