[英]MS Access: Selecting Records from 2 Tables Without Foreign Key
I'm tracking my driving habits in MS Access 2016. I have a table called Miles
: 我正在MS Access 2016中跟踪自己的驾驶习惯。我有一个名为
Miles
的表:
In my Miles
table, I'm recording information from my car's dash at the end of each drive. 在我的
Miles
表中,我正在记录每个驱动器末尾汽车破折号中的信息。
I also have a 2nd table (actually a query) called Fuel
: 我还有一个名为
Fuel
的第二张表(实际上是一个查询):
My Fuel
query shows when I purchased fuel and for how much. 我的
Fuel
查询显示了我购买燃油的时间以及购买量。
I want to create a query that shows that shows the greatest Transaction_Date
that is less than or equal to each Miles_Date
. 我想创建一个查询,该查询显示最大的
Transaction_Date
小于或等于每个Miles_Date
。 My expected output would look something like this: 我的预期输出如下所示:
I tried the following Select
statement: 我尝试了以下
Select
语句:
SELECT
Miles.Miles_ID,
DMax("[Transaction_Date]", "Fuel", "[Fuel]![Transaction_Date] <= [Miles]![Miles_Date]") AS Fuel_Date,
Miles.Miles_Date, Miles.Miles, Miles.MPG
FROM
Miles;
I get the error: 我得到错误:
Microsoft Access cannot find the name [Miles]![Miles_Date]
Microsoft Access找不到名称[Miles]![Miles_Date]
When using a domain aggregate, you need to use string concatenation to pass values from the current row, like this: 使用域聚合时,需要使用字符串连接来传递当前行中的值,如下所示:
SELECT
Miles.Miles_ID,
DMax("[Transaction_Date]", "Fuel", "[Fuel].[Transaction_Date] <= #" & Format(Miles.Miles_Date, "yyyy-mm-dd") & "#") AS Fuel_Date,
Miles.Miles_Date, Miles.Miles, Miles.MPG
FROM
Miles;
However, using a domain aggregate in a query is a bad practice, since it limits the influence of the optimizer. 但是,在查询中使用域聚合是一个坏习惯,因为它会限制优化程序的影响。 When possible, use a subquery instead:
如果可能,请改用子查询:
SELECT
Miles.Miles_ID,
(SELECT Max([Transaction_Date]) FROM Fuel WHERE [Fuel].[Transaction_Date] <= Miles.Miles_Date) AS Fuel_Date,
Miles.Miles_Date, Miles.Miles, Miles.MPG
FROM
Miles;
This will both run faster, and not rely on string concatenation. 这将运行得更快,并且不依赖于字符串连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.