How do I return a value of an entity in a table th

2019-08-05 04:24发布

问题:

I have two tables in MS Access and I am trying to add a field for one of those tables that tells which record from another table has a value that is less than the first field's value, but comes the closest? I have this query so far (just a select statement to test output and not alter existing tables), but it lists all values that are less than the querying value:

SELECT JavaClassFileList.ClassFile, ModuleList.Module
FROM JavaClassFileList, ModuleList
WHERE ModuleList.Order<JavaClassFileList.Order;`  

I tried using things likeSELECT JavaClassFileList.Classfile, MAX(ModuleList.Module), which will only display the maximum module but combined it with the select statement above, but it would say that it would only return one record.

Output desired: I have some records, a, b, and c, I shall call them, each storing various information, while a is storing a value of 732 in a column, and b is storing a value of 731 in the same column. c is storing a value of 720. In another table, d is storing a value of 730 and e is storing a value of 718. I want the output like this (they are ordered largest to smallest):

  • a 732 d 730
  • b 731 d 730
  • c 720 e 718

There can be duplicates on the right, but no duplicates on the left. How can I get this result?

回答1:

I would approach this type of query using a correlated subquery. I think the following words in Access:

SELECT jc.ClassFile,
       (select top 1 ml.Module
        from ModuleList as ml
        where ml.[Order] < jc.[Order]
       )
FROM JavaClassFileList as jc;


回答2:

I'm assuming Order is unique for Module. If it isn't, JavaClassFileRecords may show up multiple times in the resultset.

If no module can be found for a JavaClassFile then it will not show up in the results. If you do want it to show up in cases like that (with a null module), replace INNER JOIN with LEFT OUTER JOIN.

SELECT j.ClassFile, m.Module
FROM JavaClassFileList j
INNER JOIN ModuleList m
ON m.Order =
    (SELECT MAX(Order)
     FROM ModuleList
     WHERE Order < j.Order)