如何 select 来自 table 的记录在另一个 table 中没有外键
How to select records from a table which do not have foreign key in another table
我的数据库中有 5 个 table
我想 select V
中的 V_CODE
哪些记录不共享 any S
外键 F
当 F_CODE = 'A'.
我试过
select distinct V_CODE
from V
inner join V_S VS on V.V_ID = VS.V_FK
inner join S on VS.S_FK = S.S_ID
where S._ID not in (
select FS.S_FK
from F
inner join F_S on F.F_ID = F_S.F_FK
where F.F_CODE = 'A'
);
但这 return 并不是我想要的。
有人可以帮忙吗?提前致谢。
Table F
| F_ID | F_CODE |
| 1 | A |
| 2 | B |
| 3 | C |
Table F_S
| F_FK | S_FK |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
Table S
| S_ID | S_CODE |
| 1 | S1 |
| 2 | S2 |
| 3 | S3 |
Table V_S
| V_FK | S_FK |
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 3 | 1 |
| 3 | 3 |
TableV
| V_ID | V_CODE |
| 1 | V1 |
| 2 | V2 |
| 3 | V3 |
在这种情况下,我只想 return V2
因为它是 table V
中唯一不共享 Table 中的记录S
当 F_CODE = 'A'
如果我理解正确,当您遵循表之间的关系时,您希望 v_code
没有 f_code = 'A'
。
对我来说,这表明 not exists
:
select v.*
from v
where not exists (select 1
from v_s join
f_s
on v_s.s_fk = f_s.s_fk join
f
on f_s.f_fk = f.f_id
where f.f_code = 'A' and vs.v_fk = v.v_id
);
我的数据库中有 5 个 table
我想 select V
中的 V_CODE
哪些记录不共享 any S
外键 F
当 F_CODE = 'A'.
我试过
select distinct V_CODE
from V
inner join V_S VS on V.V_ID = VS.V_FK
inner join S on VS.S_FK = S.S_ID
where S._ID not in (
select FS.S_FK
from F
inner join F_S on F.F_ID = F_S.F_FK
where F.F_CODE = 'A'
);
但这 return 并不是我想要的。 有人可以帮忙吗?提前致谢。
Table F
| F_ID | F_CODE |
| 1 | A |
| 2 | B |
| 3 | C |
Table F_S
| F_FK | S_FK |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
Table S
| S_ID | S_CODE |
| 1 | S1 |
| 2 | S2 |
| 3 | S3 |
Table V_S
| V_FK | S_FK |
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 3 | 1 |
| 3 | 3 |
TableV
| V_ID | V_CODE |
| 1 | V1 |
| 2 | V2 |
| 3 | V3 |
在这种情况下,我只想 return V2
因为它是 table V
中唯一不共享 Table 中的记录S
当 F_CODE = 'A'
如果我理解正确,当您遵循表之间的关系时,您希望 v_code
没有 f_code = 'A'
。
对我来说,这表明 not exists
:
select v.*
from v
where not exists (select 1
from v_s join
f_s
on v_s.s_fk = f_s.s_fk join
f
on f_s.f_fk = f.f_id
where f.f_code = 'A' and vs.v_fk = v.v_id
);