选择不同的对值mysql

时间:2014-02-15 17:12:18

标签: mysql

我有下表,我希望提取所有独特的对:

+------+------+
| a    | b    |
+------+------+
|    1 |    2 |
|    1 |    3 |
|    1 |    6 |
|    1 |    9 |
|    2 |    1 |
|    2 |    3 |
|    3 |    1 |
|    3 |    2 |
|    4 |    1 |
|    6 |    5 |
+------+------+

输出应该是

+------+------+
| a    | b    |
+------+------+
|    1 |    2 |
|    1 |    3 |
|    1 |    6 |
|    1 |    9 |
|    2 |    3 |
|    6 |    5 |
+------+------+

3 个答案:

答案 0 :(得分:1)

试试这个:

select least(a, b) as a, greatest(a, b) as b
from table t
group by least(a, b), greatest(a, b);

这可能会产生不在原始表中的输出(例如5/6而不是6/5)。如果您想保留原始订单:

select distinct a, b
from table t
where a <= b or
      not exists (select 1 from table t2 where t2.b = t.a and t2.a = t.b);

也就是说,选择a小于或等于ba大于b的所有对,并且不存在其他行的值顺序。

答案 1 :(得分:0)

SELECT   a,b
FROM     tbl //your tableName
GROUP BY a,b
HAVING   COUNT(*) > 1

试试这个我的朋友

答案 2 :(得分:-1)

SELECT   *
FROM     NAMES2
GROUP BY Id,id2
HAVING   COUNT(*) > 1;

这个怎么样?