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),因为它们是“黄金”类型, NOT 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查询执行此操作?
答案 0 :(得分: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)
答案 1 :(得分:2)
SELECT GROUP_CONCAT(friend_id) , type FROM mytable GROUP BY type
答案 2 :(得分: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;