Expression from one query being pulled into subsequent query

人走茶凉 提交于 2019-12-24 09:18:52

问题


I have a the following tables "Base" and "Join":

Base:
ID  Field
A   1
B   2
D   

Join:
ID
A
B
C
D

I use the following select query "ExampleQuery" to parse "Base":

SELECT Base.ID, IIf(IsNull([Field]),"None",[Field]) AS Newfield
FROM Base;

And the following select query to left-join table "Join" to query "ExampleQuery":

SELECT Join.ID, ExampleQuery.Newfield
FROM [Join] LEFT JOIN ExampleQuery ON Join.ID = ExampleQuery.ID;

My output is the following:

ID  Newfield
A   1
B   2
C   None
D   None

I am expecting the value of C to be null since it was not present in the output of ExampleQuery, however it is using the logic from the expression in the original query instead. What causes this to occur, and how can I prevent it? I want to treat my initial select query strictly as a temporary table.


回答1:


You can try joining to a subquery which first replaces missing field values in the Base table with None:

SELECT t1.ID, t2.Newfield
FROM [Join] t1
LEFT JOIN
(
    SELECT ID, IIF(ISNULL([Field]),"None", [Field]) AS Newfield
    FROM Base
) t2
    ON t1.ID = t2.ID;

By the way, JOIN is a reserved keyword in Access (and probably every other version of SQL). You should avoid naming tables, columns, etc. using keywords.




回答2:


This is happening because there are two ways the field can be null: It could be null because there is a record where that field is null, or it could be because it there is no matching record at all for the outer join to find.

It does sound like you've added another table to your query, rather than joined the entire query to a table as you've stated. I think to resolve this you would need to do what you've described, which is to outer join the entire query. In Access this can be achieved by starting with your query that returns

ID  NewField
A   1
B   2
D   None

And saving it as, e.g., Query1. You would then create a new query, and include Query1 (Access treats this just like a table), then outer join it to your other table.




回答3:


Pending actual resolution, I've found a workaround by adding another condition to the expression. If I change "ExampleQuery" to:

SELECT Base.ID, IIf(IsNull([Field]) And Not IsNull([ID]),"None",[Field]) AS Newfield
FROM Base;

Then I get my desired output when I run the subsequent query matching "ExampleQuery" to table "Join":

ID  Newfield
A   1
B   2
C   
D   None


来源:https://stackoverflow.com/questions/48197991/expression-from-one-query-being-pulled-into-subsequent-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!