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

问题描述 投票:0回答:3

我有两张桌子

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

现在我想要所有从未拥有25种语音类型的租户Id。

Output:

idTenant
2
3
4

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

查询我写道:

select * from tblTenant where idTenant not in ( SELECT distinct(idTenant) FROM tblPhone where idPhoneType = 25) ;

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

.

sql sql-server
3个回答
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
投票

我们可以使用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

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
© www.soinside.com 2019 - 2024. All rights reserved.