0

単一のテーブルから組み合わせを出力するクエリがあります

Select  t1.id as id1, t2.id as id2, t3.id as id3
    mytable t1, 
    mytable t2,
    mytable t3
WHERE condition = true

テーブルに5つのエントリが含まれている場合、次のように返されます

row  id1, id2, id3

1.     1,  2,  3
2.     1,  2,  4
3.     1,  2,  5
4.     1,  3,  4
5.     1,  3,  5
6.     1,  3,  2
7.     2,  1,  3   
8.     2,  1,  4
9.     2,  1,  3
       etc....

3 つのユニークな組み合わせを除外したいので、上記の例では、行 1、6、および 7 は同じセット (すべて 1、2、および 3 を含む) であるため、そのうちの 1 つだけを保持します。

そのセットの一意の値を表す別の列を生成する方法はありますか?

たとえば、id1、id2、および id3 を並べ替えて、一意の文字列を生成することは可能ですか? (並べ替えが列でうまく機能することは知っていますが、MySQL の行では可能ですか)。GROUP_CONCAT に似ていますが、要素がソートされています。

または、重複したセットを排除する別の方法はありますか?

4

3 に答える 3

1

私は次のことを試しました:

SELECT t1.id as id1,
   t2.id as id2,
   t3.id as id3
FROM t1, t2, t3
GROUP BY MD5(t1.id+" "+t2.id+" "+t3.id)


md5(t1.id+" "+t2.id+" "+t3.id)= md5(t3.id+" "+t2.id+" "+t1.id)
=md5(t2.id+" "+t1.id+" "+t3.id)などなので、結果はおそらくあなたが必要としているものだと思います。

編集: のように、同じ id レコードを避けるために不等式も追加し
ましたWHERE t1.id <> t2.id AND t2.id <> t3.id AND t1.id <> t3.id

SQLFiddleを参照してください

于 2013-10-04T08:12:54.697 に答える
0

Ok, inspired by a the other answers I realised the easiest is to add a condition where

SELECT t1.id as id1,
   t2.id as id2,
   t3.id as id3
FROM 
    mytable t1
    mytable t2
    mytable t3
WHERE    
    id1 > id2 AND id2 > id3

It should be fast, as there are no extra calculations before filtering, and will only allow one of the combinations of the set through.

Effectively we are filtering to only allow the sorted set through.

于 2013-10-04T08:41:20.270 に答える