使用Join将子查询转换为查询

时间:2018-03-01 06:08:33

标签: sql sql-server

我有两张桌子

Scanner sc = new Scanner(System.in);

while (sc.nextLine().equals("Y")){
   // Do Stuff
}

现在我想要所有从不 语音 25

的租户ID
tblTenant

idTenant   Name
1          Hello
2          World
3          Foo 
4          Bar

tblPhone

idTenant    idPhoneType   PhoneNum
1            23             31445
1            24            43123
1            25            90899
2            23             90937
2            24             34544
4            24             23455

idTenant = 1被排除,因为它有一个phonetype = 25

的条目

查询我写道:

Output:

idTenant
2
3
4

但我想用JOINS编写这个查询。可能吗?请指导我。

3 个答案:

答案 0 :(得分:3)

使用条件聚合:

SELECT
    t1.idTenant, t1.Name
FROM tblTenant
LEFT JOIN tblPhone t2
    ON t1.idTenant = t2.idTenant
GROUP BY
    t1.idTenant, t1.Name
HAVING
    SUM(CASE WHEN t2.idPhoneType = 25 THEN 1 ELSE 0 END) = 0 AND
    COUNT(t2.idTenant) > 0;

上述问题的关键在于我们通过租户聚合tblPhone,并断言电话类型25永远不会发生。然后,我们加入tblTenant以引入实际的租户名称。

答案 1 :(得分:1)

我们可以使用Left Join -

select distinct
    T.idTenant
from tblTenant T
left join tblPhone P on P.idTenant = T.idTenant and P.idPhoneType = 25
where P.idTenant IS NULL

答案 2 :(得分:1)

试试这个:

    CREAte TAble #tblTenant(idTenant INT,Name VARCHAR(10))

    INSERT INTO #tblTenant VALUES(1,'Hello')
    INSERT INTO #tblTenant VALUES(2,'World')
    INSERT INTO #tblTenant VALUES(3,'Foo')
    INSERT INTO #tblTenant VALUES(4,'Bar')

    --SELECT * from #tblTenant

    CREATE TABLE #tblPhone(idTenant INT,idPhoneType INT,PhoneNum BIGINT)

    INSERT INTO #tblPhone vALUES(1,23,31445)
    INSERT INTO #tblPhone vALUES(1,24,43123)
    INSERT INTO #tblPhone vALUES(1,25,90899)
    INSERT INTO #tblPhone vALUES(2,23,90937)
    INSERT INTO #tblPhone vALUES(2,24,34544)
    INSERT INTO #tblPhone vALUES(4,4,23455)

    --select * from #tblPhone

    select t.idTenant from #tblTenant t
    LEFT JOIN #tblPhone p on t.idTenant=p.idTenant and p.idPhoneType=25
    WHERE p.idTenant IS NULL

    DROP TABLE #tblPhone

    DROP TABLE #tblTenant
相关问题