sql - 为 MS Access 编写 SQL 查询

标签 sql ms-access vba

我有两张 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/

相关文章:

android - 错误 "is not a JSONObject"

sql - 如何从几个可能空白的日期字段中查询最早的日期?

mysql - 将 Access 查询中的文本框值转换为mysql

excel - Powershell 脚本包括。 VBA Excel 宏

mysql - Sql - 比较两个表时数据引用不存在

sql - ORACLE中的 sleep 功能

使用角色订阅者获取用户的 SQL 查询

ms-access - MS Access "record changes"日志

excel - 使用基于动态相邻列值的 excel rank 函数

vba - Excel - VBA 宏运行后单元格被锁定