Nested Join in Excel VBA (ADODB) Results In “JOIN

2019-08-01 06:45发布

I have a series of three tables which I would like to join together using ADODB in an Excel VBA application. I am using the following query, which is resulting in the "JOIN expression not supported" error:

SELECT    tb1.date, 
          tb1.longID, 
          tb1.fld1,
          tb2.fld2,
          tb3.shortID,
          SUM(tb1.fld3) AS three, 
          SUM(tb1.fld4) AS four, 
          SUM(tb3.fld5) AS five
FROM      ([Table1$] AS tb1 LEFT JOIN [Table2$] AS tb2 ON tb1.longID = tb2.longID)
LEFT JOIN [Table3$]  AS tb3
ON        (tb3.shortID = tb2.shortID AND tb1.date = tb3.date)
GROUP BY  tb1.date, tb1.longID, tb3.shortID, tb2.fld3, tb1.fld2

If I were to omit the shortID column pair, the query works fine. If I omit the date column pair, the query works fine. But as soon as I combine the two, that's when I run into issues.

Any help would be greatly appreciated!

Thanks.

2条回答
虎瘦雄心在
2楼-- · 2019-08-01 07:10

The purpose of the ON-clause is to join 2 tables, but you try to join 3 tables at the same time with ON (tb3.shortID = tb2.shortID AND tb1.date = tb3.date). You can solve this problem in 2 ways:

  1. Move a part of the ON to the WHERE clause so that only 2 tables are involved.

    ...
    FROM      ([Table1$] AS tb1
               LEFT JOIN [Table2$] AS tb2
                   ON tb1.longID = tb2.longID)
              LEFT JOIN [Table3$] AS tb3
                  ON tb2.shortID = tb3.shortID
    WHERE tb1.date = tb3.date
    ...
    
  2. Use a sub-query

    SELECT
        x.date, 
        x.longID, 
        x.fld1,
        x.fld2,
        tb3.shortID,
        SUM(x.fld3) AS three, 
        SUM(x.fld4) AS four, 
        SUM(tb3.fld5) AS five
    FROM      
        (SELECT
             tb1.date, tb1.longID, tb1.fld1,
             tb2.fld2
         FROM
             [Table1$] AS tb1 
             LEFT JOIN [Table2$] AS tb2
                 ON tb1.longID = tb2.longID
        ) x
        LEFT JOIN [Table3$]  AS tb3
            ON (x.shortID = tb3.shortID AND x.date = tb3.date)
    GROUP BY
        x.date, x.longID, x.fld1, x.fld2, tb3.shortID
    
查看更多
倾城 Initia
3楼-- · 2019-08-01 07:14

Try to let everything inside the ON part of the query to be inside parenthesis.

The ON statement in your JOIN operation is incomplete or contains too many tables. You may want to put your ON expression in a WHERE clause.

SELECT    tb1.date, 
          tb1.longID, 
          tb1.fld1,
          tb2.fld2,
          tb3.shortID,
          SUM(tb1.fld3) AS three, 
          SUM(tb1.fld4) AS four, 
          SUM(tb3.fld5) AS five
FROM      
[Table1$] AS tb1 
LEFT JOIN [Table2$] AS tb2 ON (tb1.longID = tb2.longID)
LEFT JOIN [Table3$]  AS tb3 ON (tb3.shortID = tb2.shortID)
WHERE tb1.date = tb3.date
GROUP BY  tb1.date, tb1.longID, tb3.shortID, tb2.fld3, tb1.fld2
查看更多
登录 后发表回答