SQL配对具有交叉值的行

时间:2015-11-25 15:33:43

标签: mysql sql

我正在尝试在表格中配对两行。

ZZ  XX  PZZ  PXX 
A   B    1    2
G   E    5    9
M   N    4    4
E   H    7    4
Q   R    2    2
T   D    8    1
H   E    4    7
B   A    2    1
L   B    7    3

我想将具有相同值的行配对,但这些值会交叉到其他列,如下所示。 预期产出:

ZZ  XX  PZZ  PXX
A   B   1    2
B   A   2    1
E   H   7    4
H   E   4    7

2 个答案:

答案 0 :(得分:1)

一个简单的INNER JOIN会:

SELECT t1.ZZ, t1.XX, t1.PZZ, t1.PXX
FROM mytable AS t1
INNER JOIN mytable AS t2 
ON t1.ZZ = t2.XX AND t1.XX = t2.ZZ AND t1.PZZ = t2.PXX AND t1.PXX = t2.PZZ

ON子句在表格XXZZ之间以及PXXPZZ列之间进行交叉匹配。

Demo here

答案 1 :(得分:1)

使用EXISTS子句检查兄弟姐妹是否存在。

select *
from mytable
where exists
(
  select *
  from mytable pair
  where pair.zz = mytable.xx
    and pair.xx = mytable.zz
    and pair.pzz = mytable.pxx
    and pair.pxx = mytable.pzz
);

使用IN子句甚至更简单:

select *
from mytable
where (zz, xx, pzz, pxx) in
(
  select xx, zz, pxx, pzz
  from mytable
);

如果您希望对结果进行排序,请使用ORDER BY with LEAST AND GREATEST:

order by least(xx, zz), greatest(xx, zz), zz, least(pxx, pzz), greatest(pxx, pzz), pzz;