0

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`

順序を無視するとフィールドの組み合わせは同じになるため、1 行のみを返すようにしたいと思います。

これについてどうすればいいですか?

4

3 に答える 3

1

If you have only two columns, this is easy:

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

With three, this is a bit harder:

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;

Note that distinct is a more succinct way of getting distinct groups.

EDIT:

If you want to do this for more columns, MySQL doesn't offer the nth() function (analogous to least() and greatest(). You can do the following. Unpivot the values (assuming there is an id on each row), then use group_concat() with the order by option:

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;

This will give you back the values as a comma separated list.

于 2013-09-04T11:12:01.883 に答える
0

mysql サーバーで使用される関数を記述すること以外に、次のように SQL と PHP の両方を組み合わせて使用​​することしか考えられません。

SELECT distinct
    `no1`, `no2`, `no3`
FROM  `items` 

これにより、分離された行が得られるので、このトリックを実行できます。それを配列にポップし、各行を並べ替えます。

$array=(0 => 'C', 1 => 'B', 2 => 'A');
sort($array);

すべての新しいビットを単一の多次元配列に収集し、それらにarray_uniqueを使用して、必要な個別の値のみを取得します。

MYSQL で列をアルファベット順に並べ替える同じ機能を複製することもできますが、これは非常に難しいことは間違いありません。

于 2013-09-04T11:08:59.057 に答える
0

それを試してください:

SELECT group_concat(concat(`no1`, `no2`, `no3`) as STH
FROM  `items` 
GROUP BY `no1', `no2`, `no3`
于 2013-09-04T11:09:03.513 に答える