mysql - 按任意顺序对多行进行分组

标签 mysql select

我正在使用Mysql和PHP

如果我有一张 table

-------------------
| no1 | no2 | no3 | 
|-----|-----|-----|
|  A  |  B  |  C  |
|  B  |  C  |  A  |
|  C  |  B  |  A  |
-------------------

我想返回行的唯一组合

SELECT `no1`, `no2`, `no3`
FROM  `items` 
GROUP BY `no1', `no2`, `no3`

我希望它只返回一行,因为如果忽略顺序,字段的组合是相同的。

我该如何解决这个问题?

最佳答案

如果您只有两列,这很简单:

select distinct least(col1, col2), greatest(col1, col2)
from t;

对于三个,这有点困难:

select distinct least(no1, no2, no3) as smallest,
       (case when no1 not in (least(no1, no2, no3), greatest(no1, no2, no3)) then no1
             when no2 not in (least(no1, no2, no3), greatest(no1, no2, no3)) then no2
             else no3
        end) as middle,
      greatest(no1, no2, no3) as biggest
from items;

请注意,distinct 是获取不同组的更简洁的方法。

编辑:

如果您想对更多列执行此操作,MySQL 不提供 nth() 函数(类似于 least()greatest() 。您可以执行以下操作。对值进行逆透视(假设每行都有一个 id),然后将 group_concat()order by 选项结合使用:

select distinct nos
from (select id, group_concat(noi order by noi) as nos
      from (select id,
                   (case when n.n = 1 then no1
                         when n.n = 2 then no2
                         when n.n = 3 then no3
                    end) as noi
            from items i cross join
                 (select 1 as n union all select 2 union all select 3) n
           ) nn
      group by id
     ) nn;

这将以逗号分隔列表的形式返回值。

关于mysql - 按任意顺序对多行进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18612019/

相关文章:

php - 如何连接到另一个域上的 MySQL 数据库?

php - 两种方式的数据库加密甚至对管理员都是安全的

php - 通过 php 和 html 表单上传文件的代码错误

postgresql - 在 Postgres 中创建函数时出错

php - 页面加载时重新加载下拉菜单

mysql - 如何计算从页表中获取的记录数?

c# - Entity Framework 模型优先设计中的存储库模式

mysql - case 表达式中的求和列

sql - 使用直线时避免在列名中打印表名

mysql - 在 Codeigniter 中选择具有事件记录的当前用户