检查两个人是否在SQL中共享同一个电话号码

时间:2016-03-14 02:52:52

标签: mysql sql

所以我有一张包含学生ID和电话号码的表格。有些学生共用同一个电话号码,我想选择并显示这些学生。

例如。

+-----------+-----------+--------------+
| StudentID | StudentID | PNumber      |
+-----------+-----------+--------------+
|      1000 |      1000 | 970-555-1000 |
|      1000 |      1000 | 970-555-1010 |
|      1100 |      1100 | 970-555-1100 |
|      1200 |      1200 | 303-555-1200 |
|      1200 |      1300 | 303-555-1200 |
|      1300 |      1200 | 303-555-1200 |
|      1300 |      1300 | 303-555-1200 |
|      1300 |      1300 | 303-555-1210 |
|      1400 |      1400 | 970-555-1400 |
|      1500 |      1500 | None         |
|      1600 |      1600 | 970-555-1600 |
|      1600 |      1700 | 970-555-1600 |
|      1700 |      1600 | 970-555-1600 |
|      1700 |      1700 | 970-555-1600 |
|      1800 |      1800 | 970-555-1800 |
|      1900 |      1900 | 970-555-1900 |
|      2000 |      2000 | 970-555-2000 |
|      2000 |      2000 | 970-555-2010 |
|      2001 |      2001 | 970-555-2001 |
+-----------+-----------+--------------+

这应输出:

1200 | 1300 | 303-555-1200
1300 | 1200 | 303-555-1200
1600 | 1700 | 970-555-1600
1700 | 1600 | 970-555-1600

2 个答案:

答案 0 :(得分:1)

使用自我加入:

SELECT
    s1.StudentID, s2.StudentID, s1.PNumber
FROM
    students s1 INNTER JOIN students s2 USING(StudentID)
WHERE s1.PNumber = p2.PNumber;

答案 1 :(得分:1)

尝试加入自己:

select t1.StudentID,t2.StudentID,t1.PNumber
from Student t1
join Student t2 on t1.PNumber= t2.PNumber
where t1.StudentID <> t2.StudentID