gpt4 book ai didi

MYSQL GROUP BY 具有特定列的多个不同值

转载 作者:行者123 更新时间:2023-11-29 01:11:37 24 4
gpt4 key购买 nike

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),因为它们是“黄金”类型,不是按类型分组

返回结果:

 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

最佳答案

您需要做的是根据类型添加额外的分组子句。当它是“黄金”时,你会得到一个常数。否则,您使用 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)

关于MYSQL GROUP BY 具有特定列的多个不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14296545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com