Mysql 按任意顺序按多行分组

Mysql 按任意顺序按多行分组,mysql,select,Mysql,Select,我正在使用Mysql和PHP 如果我有桌子 ------------------- | no1 | no2 | no3 | |-----|-----|-----| | A | B | C | | B | C | A | | C | B | A | ------------------- 我想返回行的唯一组合 SELECT `no1`, `no2`, `no3` FROM `items` GROUP BY `no1', `no2`, `no3` 我希望

我正在使用Mysql和PHP

如果我有桌子

-------------------
| no1 | no2 | no3 | 
|-----|-----|-----|
|  A  |  B  |  C  |
|  B  |  C  |  A  |
|  C  |  B  |  A  |
-------------------
我想返回行的唯一组合

SELECT `no1`, `no2`, `no3`
FROM  `items` 
GROUP BY `no1', `no2`, `no3`
我希望它只返回一行,因为如果忽略顺序,字段的组合是相同的


我该怎么做呢?

除了编写mysql服务器使用的函数外,我唯一能想到的就是使用SQL和PHP的组合,如下所示:

SELECT distinct
    `no1`, `no2`, `no3`
FROM  `items` 
这将给出disict行,然后我们可以执行此技巧。将其放入数组并对每行进行排序:

$array=(0 => 'C', 1 => 'B', 2 => 'A');
sort($array);
将所有新位收集到一个多维数组中,并对其使用一个数组,以仅获取所需的不同值

您也可以在MYSQL中复制按字母顺序排列列的相同功能,尽管这无疑是相当棘手的。

试试:

SELECT group_concat(concat(`no1`, `no2`, `no3`) as STH
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()
magest()
。您可以执行以下操作。取消输入值(假设每行上都有一个id),然后使用
group\u 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;

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

您的查询将准确返回您的输入表。因为如果您为所有字段分组,您就不会分组!