30

我是 sql 新手,所以请善待。

假设我必须显示所有具有相同电话号码的employee_ids(两列都在同一个表中)

我该如何处理这个问题内部连接或其他东西。

4

4 回答 4

39
SELECT * FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

更新:为了更好的性能和更快的查询,最好e1在 * 之前添加

SELECT e1.* FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;
于 2014-11-13T15:03:55.317 回答
37

怎么样

SELECT *
FROM Employees
WHERE PhoneNumber IN (
    SELECT PhoneNumber
    FROM Employees
    GROUP BY PhoneNumber
    HAVING COUNT(Employee_ID) > 1
    )

SQL 小提琴演示

于 2013-09-16T18:19:22.997 回答
1

你可以做到这一点没有JOIN

SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
      FROM YourTable
      )sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids

演示: SQL 小提琴

于 2013-09-16T18:20:17.893 回答
-1
select *
from Table1 as t1
where
    exists (
        select *
        from Table1 as t2 
        where t2.Phone = t1.Phone and t2.id <> t1.id
    )

sql fiddle demo

于 2013-09-16T18:28:36.743 回答