MySQL查询列a中的项目选择b中的项目,反之亦然

时间:2012-04-25 23:05:28

标签: mysql

我有两列数据

Refer > Target
1 > 4
1 > 7
2 > 5
3 > 6
4 > 1

我想在MySQL中运行一个查询,选择每个也由其目标选择的引用。那么,1> 4和4> 1.

我能得到的最好的是:

SELECT refer FROM table WHERE refer IN
(SELECT target FROM table)

但是,这只是列出了另一列中的内容,而不是匹配的内容。

3 个答案:

答案 0 :(得分:1)

SELECT DISTINCT t1.*
FROM myTable t1
JOIN myTable t2
  ON t1.Refer = t2.Target
  AND t1.Target = t2.Refer

答案 1 :(得分:0)

我认为不需要过度复杂化这个查询

SELECT refer FROM TABLE WHERE (refer = '1' and target = '4') or (refer ='4' and target = '1')

答案 2 :(得分:0)

您可以使用自联接:

SELECT a.refer, a.target FROM tbl a
INNER JOIN
(
    SELECT refer, target FROM tbl
) b

ON a.target = b.refer AND a.refer = b.target