我有两张 table
table1 tbl指令
inst_id instruction
1 aaaaa
2 bbbbb
3 cccccc
4 ddddd
5 eeeee
6 fffff
7 ggggg
8 hhhhh
9 iiiii
10 jjjjj
表2 tblDischarge
d_id inst_id1 inst_id2 inst_id3 inst_id4
1 3 5 2 8
2 5 7 1 10
3 10 2 8 7
4 6 8 4 3
5 9 1 3 5
我需要获取基于 d_id = 2 的 inst_id1、inst_id2、inst_id3、inst_id4 的所有指令
预期输出
eeeee
ggggg
aaaaa
jjjjj
我正在尝试编写一个 SQL 查询来获取上述输出。我正在使用 MS Access,我需要在 MS Access VBA 程序中使用此 SQL 查询。
我尝试了下面两个使用 In() 和 Exists() 的 SQL 查询,我得到了所有指令,而不是特定指令。
select instruction from tblInstruction where inst_id
in (select inst_id1,inst_id2,inst_id3,inst_id4 from tblDischarge where d_id = 2);
select instruction from tblInstruction where
exists(select inst_id1,inst_id2,inst_id3,inst_id4 from tblDischarge Where d_id = 2);
最佳答案
也许最有效的方法是使用exists
:
select i.*
from tblInstruction as i
where exists (select 1 from tblDischarge as d where d.d_id = 2 and i.inst_id = d.inst_id1
) or
exists (select 1 from tblDischarge as d where d.d_id = 2 and i.inst_id = d.inst_id2
) or
exists (select 1 from tblDischarge as d where d.d_id = 2 and i.inst_id = d.inst_id3
) or
exists (select 1 from tblDischarge as d where d.d_id = 2 and i.inst_id = d.inst_id4
);
请注意,您的数据模型非常差。最好有一个连接表,每个指令/放电对都有单独的行。
编辑:
更好的结构是有一个连接表 instutionDischarge
,其中包含如下列:
institutionDischargeId
d_id
inst_id
计数器
——或者类似的东西
关于sql - 为 MS Access 编写 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51651149/