繁体   English   中英

"MS Access:如何在第一个表中找不到值时查询第二个表"

[英]MS Access: How to query a second table when value is not found in the first

我有一个简单的查询来查找相关表中的值。 在某些情况下,该值为空。 在这种情况下,我想查询第二个表。 我查看了 NZ 函数,但它不允许进行其他查询操作。 我假设我正在查看嵌套查询或 SQL COALASCE 之类的操作。

我想先搜索 tbl_bi_item_mstr

SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_bi_item_mstr.bi_item_nr
FROM tbl_cust_fcst_demd LEFT JOIN tbl_bi_item_mstr ON tbl_cust_fcst_demd.cust_item_nr = tbl_bi_item_mstr.bi_item_nr;

对于空值,我想在 tbl_cust_xref 中找到它们

SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_cust_xref.bi_item_nr
FROM tbl_cust_fcst_demd INNER JOIN tbl_cust_xref ON tbl_cust_fcst_demd.cust_item_nr = tbl_cust_xref.cust_item_nr;

条件查询可能很棘手,您可以在宏或 vba 等中进行,但这需要在 sql 语句之外完成。 如果您希望保持简单,我建议将 2 个表与不同的列合并。

下面联合的示例代码:

SELECT 
tbl_cust_fcst_demd.cust_item_nr
, tbl_bi_item_mstr.bi_item_nr
, 1 as "src_priority"
FROM tbl_cust_fcst_demd LEFT JOIN tbl_bi_item_mstr ON tbl_cust_fcst_demd.cust_item_nr = tbl_bi_item_mstr.bi_item_nr

Union

SELECT tbl_cust_fcst_demd.cust_item_nr
, tbl_cust_xref.bi_item_nr
, 2 as "src_priority"
FROM tbl_cust_fcst_demd INNER JOIN tbl_cust_xref ON tbl_cust_fcst_demd.cust_item_nr 

Order by src_priority

您可以简单地连接两个表,并在结果字段之间使用Nz()<\/code> 。

SELECT d.cust_item_nr, Nz(i.bi_item_nr, x.bi_item_nr) AS bi_item_nr
FROM (tbl_cust_fcst_demd d 
LEFT JOIN tbl_bi_item_mstr i ON d.cust_item_nr = i.bi_item_nr)
INNER JOIN tbl_cust_xref x ON d.cust_item_nr = x.cust_item_nr

安德烈的建议很有帮助。 需要 INNER JOIN 才能更改为 LEFT JOIN 或忽略空值。

SELECT d.cust_item_nr, Nz([i].[bi_item_nr],[x].[bi_item_nr]) AS bi_item_nr
FROM (tbl_cust_fcst_demd AS d 
LEFT JOIN tbl_bi_item_mstr AS i ON d.cust_item_nr = i.bi_item_nr) 
LEFT JOIN tbl_cust_xref AS x ON d.cust_item_nr = x.cust_item_nr

暂无
暂无

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

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