查找数据表中互为配对记录的SQL查询需求
Find Mutually Paired Records in SQL
First, let's assume your table is named your_table (swap this out for your actual table name if it's different). Based on your data and requirements, here's a clean SQL query that will pull the exact paired records you're looking for:
SELECT t1.A, t1.B FROM your_table t1 INNER JOIN your_table t2 ON t1.A = t2.B AND t1.B = t2.A;
How this works:
- We use a self-join (joining the table to itself) to compare each row against every other row in the dataset.
- The join condition
t1.A = t2.B AND t1.B = t2.Aacts as a filter: it only keeps rows where there’s a matching "reverse" pair (so if rowt1has values (x,y), there must be a rowt2with (y,x)).
Testing with your sample data:
For your provided rows:
| A | B |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 4 | 5 |
| 2 | 1 |
| 5 | 6 |
| 7 | 6 |
| 6 | 5 |
This query will return exactly the pairs you expect:
(1,2), (2,1), (5,6), (6,5)
Rows like (2,3), (4,5), and (7,6) get excluded automatically—since there’s no corresponding reverse pair in the table, they don’t meet the join condition.
内容的提问来源于stack exchange,提问作者matei basar
相关产品推荐
相关产品推荐

