0

假设有一个名为 Stack 的表;

Id       StackId
-------------------
.             .
1             10
2             12
3             10
4             10
5             11
11            5
.             .
.             .

如何学习cross id之类的?

Id = 5
StackId = 11

Id = 11
StackId = 5

我不能写给我看的sql语句

5,11
11,5 

我不知道数字,因为表格有 1.000.000+ 行,所以我想找到喜欢 5,11 的行

4

4 回答 4

3

用于带有条件JOIN的表本身:s1.Id = s2.StackId AND s1.StackId = s2.Id

SELECT s1.Id, s1.StackId
FROM Stack s1
JOIN Stack s2 ON s1.Id = s2.StackId AND s1.StackId = s2.Id

因为INNER JOIN已使用(默认情况下)没有相应s2值的行将不会被返回。

于 2013-04-16T10:55:18.490 回答
1

请试试:

select a.* from 
    YourTable a inner join YourTable b on a.Id=b.StackId
于 2013-04-16T10:57:18.903 回答
1

您可以使用聚合和连接来解决此问题。这是一种方法:

select (case when id < StackId then id else StackId end) as FirstVal,
       (case when id < StackId then StackId else id end) as SecondVal
from t
group by (case when id < StackId then id else StackId end),
         (case when id < StackId then StackId else id end)
having count(distinct id) = 2

如果您有一个带有 aleast()greatest()函数的数据库,并且您知道表中现在有重复项,则可以将其改写为:

select least(id, StackId) as FirstVal, greatest(id, StackId) as SecondVal
from t
group by least(id, StackId), greatest(id, StackId)
having count(*) = 2
于 2013-04-16T11:02:09.753 回答
1

另一种解决方案:

select *
from Stack s
where exists (select 1 from Stack where Id = s.StackId and StackId = s.Id)
于 2013-04-16T11:04:44.143 回答