Mysql 如何解决SQL单对问题

Mysql 如何解决SQL单对问题,mysql,sql,Mysql,Sql,嗨,我的问题是我必须列出所有的单恋关系(A喜欢B,但B不喜欢A) 在这个例子中,我的解决方案是一对31(因为1喜欢2,2也喜欢1) 我应该如何以SQL的形式表示它呢?您可以使用不匹配的id A | B -: | -: 3 | 1 dbfiddle您可以用与编写问题非常相似的方式来表达查询。您正在查找不存在“B喜欢A”行的“A喜欢B”行 假设该表的名称为mytable: select * from mytable t1 where not exists ( select * from m

嗨,我的问题是我必须列出所有的单恋关系(A喜欢B,但B不喜欢A)

在这个例子中,我的解决方案是一对31(因为1喜欢2,2也喜欢1)
我应该如何以SQL的形式表示它呢?

您可以使用不匹配的id

A | B -: | -: 3 | 1
dbfiddle

您可以用与编写问题非常相似的方式来表达查询。您正在查找不存在“B喜欢A”行的“A喜欢B”行

假设该表的名称为
mytable

select *
from mytable t1
where not exists (
  select *
  from mytable t2
  where t1.A = t2.B and t1.B = t2.A
);

使用只返回不匹配行的self
LEFT
联接:

select t1.*
from tablename t1 left join tablename t2
on t2.a = t1.b and t2.b = t1.a
where t2.a is null
请参阅。
结果:


MySQL方便地支持在中使用
的元组。因此,一种方法是:

select t.*
from t
where (b, a) not in (select a, b from t);
一个警告是,如果
a
b
NULL
(但我猜在本例中不可能是这样)

作为一般规则,我建议使用
不存在(…)
A | B -: | -: 3 | 1
select *
from mytable t1
where not exists (
  select *
  from mytable t2
  where t1.A = t2.B and t1.B = t2.A
);
select t1.*
from tablename t1 left join tablename t2
on t2.a = t1.b and t2.b = t1.a
where t2.a is null
| A   | B   |
| --- | --- |
| 3   | 1   |
select t.*
from t
where (b, a) not in (select a, b from t);