简体   繁体   English

SQL SELECT表达式-在3个表之间进行选择

[英]SQL SELECT expression- select between with 3 tables

I have tables 我有桌子

T1: T1:

T1ID

1000
1001
1002
1003

T2: T2:

T2ID     T1ID

W1       1000
W2       1000
W3       1001
W4       1002
W5       1003

T3: T3:

T3ID   STATUS   T2ID

T1     CLOSE    W1
T2     CLOSE    W1
T3     INPRG    W3
T4     INPRG    W3
T5     CLOSE    W5
T6     INPRG    W5

I want to make expression to get as result only 1000 and 1002 from T1. 我想使表达式仅从T1获得1000和1002。 As result from T1 select I want to get records that either in T2 have T2 records for which all T3 records are in CLOSE status or T2 records do not have T3 records at all. 作为T1选择的结果,我想获取以下记录:T2中具有T2记录,而所有T3记录都处于CLOSE状态,或者T2记录根本没有T3记录。

So 1000 has W1 which has all T3 records in CLOSE and W2 which does not have T3 records. 因此1000有W1,其中W1具有所有CLOSE中的T3记录,W2没有W3记录。 Also 1002 have W4 record which does not have T3 records. 同样1002具有W4记录,而没有T3记录。 So they must be selected. 因此必须选择它们。

1001 must not be selecet beacuse it has W3 record for which all T3 records are not CLOSEd. 不能选择1001,因为它具有未关闭所有T3记录的W3记录。 1003 also must not be selected because it has W5 for which all T3 records are not closed. 也不要选择1003,因为它具有W5,但尚未关闭所有T3记录。

It is little tricky for me. 对我来说,这有点棘手。

Thank you 谢谢

Select distinct t1.id
From   t1
       Inner join
       T2 on t1.id=t2.t1id
       Left join
       (Select t3.t3id 
        from T3 
        where t3.status <> 'CLOSE') t3a on t3a.t3id=t2.t3id and t3.t3id is null

Written on a tablet so please forgive/correct the capitalisation. 写在平板电脑上,请原谅/更正大写。

So you want all records from T1 where there are either ONLY closed T3 records, or no T3 records, where T3 is linked to T1 via T2. 因此,您需要来自T1的所有记录,其中只有关闭的T3记录,或者没有T3记录,其中T3通过T2链接到T1。 Conversely, you want all T1 records EXCEPT those where you have non-closed T3 records. 相反,除了那些未关闭的T3记录,您都希望所有T1记录。

Expressing it both ways gives different ways to write the same query. 两种方式都表达它可以提供不同的方式来编写相同的查询。 For example you could do 例如你可以

SELECT t1.id
FROM t1
where not exists(
  select * 
  from t2
    inner join t3
      on t2.id = t3.t2id
  where t3.status <> 'CLOSE'
  )

Alternatively you could do 或者你可以做

select t1.id
from t1
EXCEPT
select t1.id
from t1
  inner join t2
    on t1.id = t2.t1id
  inner join t3
    on t2.id = t3.t2id
where t3.status <> 'CLOSE'

You can ask SQL Server Management Studio to tell you which one is more efficient - they may well end up executing with the same query plan. 您可以要求SQL Server Management Studio告诉您哪个效率更高-他们最终可能会以相同的查询计划执行。

(not tested but I think the syntax above is ok) (未经测试,但我认为上面的语法还可以)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM